接口
语法:
interface 接口名{
//属性
//方法
}
【说明】
- 在JDK7.0之前,接口中的所有方法都是抽象方法,即无方法体
- 在JDK8.0包括8.0之后,接口中可以有抽象/静态/默认方法(需要修饰符
default
),即方法体可有可无
interface USB{
int i = 0;//必须赋值
void A();
default void B(){
System.out.print("this id B()");
}
static void C(){
System.out.print("this is C()");
}
}
实现接口:
class 类名 implements 接口{
//自身属性
//自身方法
//实现接口中的所有方法
}
- 接口
① 接口中所有方法都是public
的;接口中抽象方法可以不用abstract
② 接口中的属性都是public static final
的,所以必须定义时初始化
③ 接口的修饰符号只能是默认和public
的 - 接口的实现
① 接口不能被实例化
② 普通类实现接口必须实现接口中的所有方法(快捷键alt+enter)
③ 抽象类实现接口可以不实现接口的抽象方法
④ 一个类可以有多个接口
⑤ 接口中属性的访问形式:接口名.属性名 - 接口与接口与类之间的关系
接口和接口之间可以继承;类实现接口
接口与继承的区别
实现接口是对Java单继承机制的一种补充:当子类继承了父类,就自动拥有父类的功能;如果子类需要扩展功能,可以通过实现接口的方式扩展
接口的多态性
- 多态参数
interface A{}
class B implements A{}
class C implements A{}
class AA{}
class BB extends AA{}
class CC extends AA{}
public class InterfacePolyParameter {
public static void main(String[] args) {
//接口的多态体现
//接口类型的变量a 可以指向 实现了A接口的对象实例
A a=new B();
a=new C();
//继承的多态体现
//父类类型的变量aa 可以指向 继承了父类AA的子类的对象实例
AA aa=new BB();
aa=new CC();
}
}
- 多态数组
interface D{}
class E implements D{}
class F implements D{}
public class InterfacePolyArray {
public static void main(String[] args) {
//方法一:
D[]d1=new D[2];
d1[0]=new E();
d1[1]=new F();
//方法二:
D[ ]d2={new E(), new F() };
}
}
- 多态传递
interface J{}
interface K extends J{}
class L implements K{}
public class InterfacePolyPass {
public static void main(String[] args) {
K k=new L();
J j=new L();
}
}
关系图:
练习
以下程序的运行结果为?
interface A{ int a=1; } class B implements A { } public class InterfaceExercise { public static void main(String[] args) { B b = new B(); System.out.println(A.a); System.out.println(B.a); System.out.println(b.a); } }
A类中的a是pubilc static final int
类型,所以以上语法都正确且输出都为1
interface G { int x=0; } class H{ int x=1; } class I extends H implements G{ void getX(){ System.out.println(x); } } public class InterfaceExercise02 { public static void main(String[] args) { I i = new I(); i.getX(); } }
I类继承了H又有接口G,其中H和G都有属性x,这时就会导致指向不明确
接口中的x类型为public static final
,因此可以用接口名.属性的方式直接引用;对于父类的属性,可以利用super
调用
class I extends H implements G{
void getX(){
System.out.println(G.x+" "+super.x);
}
}