接口是一种特殊的抽象类,里面所有的变量都是全局变量,所有的方法都是抽象方法
1 public class InterfaceTest { 2 public static void main(String[] args) { 3 A c1 = new c(); 4 c1.method(); 5 B c2 = new c(); 6 //c1.printInfo();//result:找不到符号 方法printInfo() 7 c2.printInfo(); 8 System.out.println(c1.MAX); 9 } 10 } 11 12 interface A { 13 int MAX = 99999;//接口里的成员变量都是常量,默认声明是public static final的。也只能是这样的。 14 void method(); //接口里的方法都是抽象abstract方法,默认声明是public abstract。也只能是public abstract的。 15 } 16 17 interface B { 18 void printInfo(); 19 } 20 21 class c implements A,B { 22 public void method() { 23 System.out.println("Hello Word!"); 24 } 25 public void printInfo() { 26 System.out.println("你好"); 27 } 28 } 29 30 /* 31 1.接口是一种特殊的抽象类,里面的所有的成员变量是全局变量,里面所有的方法都是抽象方法。换句话说:接口就是被子类用来实现的。 32 2.接口里面的成员变量默认声明是public static final的,里面的方法默认是public abatract的。如果不写也是public的。 33 结果:Hello Word! 34 99999 35 3.接口解决了java的单继承局限,一个类可以实现多个接口。实现多个接口,则必须把所有接口包含的方法全部重写覆盖。 36 */
java抽象类与接口
1 public class InterfaceTest { 2 public static void main(String[] args) { 3 A d1 = new D(); 4 d1.aPrint(); 5 6 F d2 = new D(); 7 d2.fPrint(); 8 } 9 } 10 11 interface A { 12 void aPrint(); 13 } 14 15 interface B { 16 void bPrint(); 17 } 18 19 interface C extends A,B { 20 void cPrint(); 21 } 22 23 interface E { 24 void ePrint(); 25 } 26 27 abstract class F implements E { 28 abstract void fPrint(); 29 } 30 31 class D extends F implements C { 32 public void aPrint() { 33 System.out.println("D aPrint"); 34 } 35 public void bPrint() { 36 System.out.println("D bPrint"); 37 } 38 public void cPrint() { 39 System.out.println("D cPrint"); 40 } 41 public void ePrint() { 42 System.out.println("D eprint"); 43 } 44 public void fPrint() { 45 System.out.println("D fprint"); 46 } 47 } 48 /* 49 1.接口可以继承其他接口,接口可以多重继承。(java中类只能单继承)。 50 2.如果一个接口 C 同时继承了其他接口,那么当实现C接口时必须把C接口及C接口所有继承接口中的全部方法重写覆盖实现。 51 3.抽象类可以实现接口。 52 */
implements与extends的进一步探究:
public class Test { public static void main(String[] args) { E d1 = new D(); C d2 = new D(); d1.aPrint(); d2.aPrint(); } } interface A { void aPrint(); } interface B { void bPrint(); } abstract class C implements A,B {//这里implements 不能换成extends public abstract void cPrint(); } interface E extends A,B { void ePrint(); } class D extends C implements E { public void aPrint() { System.out.println("aPrint"); } public void bPrint() { System.out.println("bPrint"); } public void cPrint() { System.out.println("cPrint"); } public void ePrint() { System.out.println("ePrint"); } } /* 1.重写接口的方法,方法的声明必须是public的,因为子类方法的权限要大于父类。 2.extends只能有一个,implements允许有多个,这点在interface上是个例外。接口可以extends多个接口。 */