接口(interface)


本質

本質上就是一個寬泛的抽象類

作用


public interface Shape1 {
 int a=1;
	//系統自動增加成為:
	//   public static final int a=1;
	 double length();
  double area();
  //系統自動添加成為:
	// public abstract double area();
}

使用1

public class Trigangle implements Shape1 {

	//Shape 里面有a,不能與Shape里面的變量重名
	int a1;
	int a2;
	int a3;
	public Trigangle()
	{
		this(a,a,a);
	}

	public Trigangle(int a1, int a2, int a3) {
		super();
		this.a1=a1;
		this.a2=a2;
		this.a3=a3;
	}

	public double length() {
		return a1+a2+a3;
	}

	public double area() {
		double p=length()/2;
		return Math.sqrt(p*(p-a1)*(p-a2)*(p-a3));
	}

}

使用2


public class ShapeTest {

	public static void main(String[] args) {
		Shape1 shape;
		shape =new Trigangle();//此時接口相當於上轉型對象
		System.out.println(shape.area());//多態
		System.out.println(shape.length());
		shape =new Y();
		System.out.println(shape.area());
		shape= new C();
		System.out.println(shape.area());
	}
}

優點(比較抽象類)

一個類可以繼承一個類,但可以同時實現(繼承)多個接口

public class Child extends Fathter implements Shape1,Interface1{
}

接口可以繼承多個接口

public interface Interface2 extends Interface1,Shape1{
}

匿名內部類

(類沒有名字)(用接口創建了一個上轉型對象)

和普通類對比

普通類可以創建多個對象,而匿名內部類只能創建一個

舉例

接口:Shape

package prj4;

public interface Shape {   
	
	int a=1;        //public static final
	
	double length();
	double area();  //public abstract 
	
}

主函數

package prj4;


public class Graph {
	
	public static void main(String[] args) {
		Shape shape1=new Shape() {

			public double length() {
				// TODO Auto-generated method stub
				return 10;
			}

			public double area() {
				// TODO Auto-generated method stub
				return 1010;
			}
		};
		System.out.println(shape1.area());
		System.out.println(shape1.length());
	}
}

實戰

計算各種圖形的周長 <接口|繼承|多態|分割字符串>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM