java中的接口

java中的接口使用interface来定义,类似于类的定义,有接口名称和接口体

[修饰符] interface 接口名 extends 父接口名列表{

[public] [static] [final] 常量;
[public] [abstract] 方法;
}

接口体中不能有变量,可以有常量。方法只能是虚方法,不能实现,具体的实现要在类中实现

与Java的类文件一样,接口文件的文件名必须与接口名相同

接口在定义后,就可以在类中实现该接口。在类中实现接口可以使用关键字implements,其基本格式如下:


[修饰符] class <类名> [extends 父类名] [implements 接口列表]{
}

接口存在的具体作用是什么,一种是补充JAVA只能继承一个父类,不能像C++一样继承多个父类,

接口却可以,可以继承多个接口。

另外,接口的定义里只能有虚函数,具体的函数实现要在实现他的类中去

实现,那这样接口有什么意义,每个实现这个接口的类还是要重写接口函数,

这样的话可以不要接口,直接在类中定义这个函数不就行了?

接口的主要作用可以达到统一访问,创建对象的时候接口创建

【接口名】 【对象名】=new 【实现接口的类】

interface if1{
void method();
}
class A implements if1{
public void method(){
System.out.println("this is A.method()");
}
}
class B implements if1{
public void method(){
System.out.println("this is B.method()");
}
}
public class InterfaceTest{
public static void main(String[] args){
if1 aA=new A();
if1 aB=new B();
if1 commonIF1;
commonIF1=aA;
commonIF1.method();
commonIF1=aB;
commonIF1.method();

}
}

另外一种方式:

interface If1 {
public void play();
}
class Cl1 implements If1{
public void play() {
System.out.println("this is class 1");
}
}
class Cl2 implements If1{
public void play() {
System.out.println("this is class 2");
}
}
public class InterfaceTest2 {
public static void main(String[] args) {
If1 aIf1_1 = new Cl1();
If1 aIf1_2 = new Cl2();
Cl1 aCl1_1 = new Cl1();
Cl2 aCl2_1 = new Cl2();
show(aIf1_1);
show(aIf1_2);
show(aCl1_1);
show(aCl2_1);
}
public static void show(If1 if1){
if1.play();
}
}

posted on 2015-01-21 16:20  wudymand  阅读(247)  评论(0编辑  收藏  举报

导航