本质

本质上就是一个宽泛的抽象类

作用

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{
}


注意:下面三个都是上转型变量,但是并不相同

public class Test {

public static void main(String[] args) {
Fathter a=new Child();
//a 能调用Father的所有方法

Shape1 aa=new Child();
//aa 能调用Shape1的所有方法

Interface1 aaa=new Child();
//aaa 能调用Interface1的所有方法


}
}

package sdut.W;

public class Test {

public static void main(String[] args) {
AA aa=new AA();

System.out.println(aa.a);
System.out.println(aa.b);
aa.m1();
aa.m2();
System.out.println("=================================");
BB bb=new BB();
System.out.println(bb.a);
System.out.println(bb.b);
System.out.println(bb.c);
bb.m1();
bb.m2();
bb.m3();
System.out.println("=================================");

AA ab=new BB();
System.out.println(ab.a);
System.out.println(ab.b);//父类的属性
//编译错误 System.out.println(ab.c);
ab.m1();
ab.m2();//子类的方法
//编译错误 ab.m3();

//编译错误 BB ba=new AA();



}
}