abstract class 和interface的区别
1 package com.action; 2 3 public interface InterfaceTest { 4 5 public abstract void fun1(); 6 7 void fun2(); // 默认的都是public,abstract 类型的 8 9 void fun3(); 10 11 int i = 10; // 默认的都是public static final 型 12 }
1 package com.action; 2 3 public class Test1 implements InterfaceTest { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 Test1 test1 = new Test1(); 11 test1.fun1(); 12 System.out.println(test1.i); 13 14 } 15 16 @Override 17 public void fun1() { 18 // TODO Auto-generated method stub 19 System.out.println("fun1"); 20 } 21 22 @Override 23 public void fun2() { 24 // TODO Auto-generated method stub 25 System.out.println("fun2"); 26 } 27 28 @Override 29 public void fun3() { 30 // TODO Auto-generated method stub 31 System.out.println("fun3"); 32 } 33 34 }
1 package com.action; 2 3 public abstract class AbstractClass { 4 5 void fun1() { 6 System.out.println("fun1"); 7 } 8 public abstract void fun2(); 9 10 public int i=01; 11 }
1 package com.action; 2 3 public class Test2 extends AbstractClass { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 Test2 test2 = new Test2(); 11 test2.fun1(); 12 test2.fun2(); 13 test2.i=2; 14 System.out.println(test2.i); 15 } 16 17 @Override 18 public void fun2() { 19 // TODO Auto-generated method stub 20 System.out.println("fun2"); 21 } 22 23 }
1.abstract class 在 Java 语言中表示的是一种继承关系,一个类只能使用一次继承关系。但是,一个类却可以实现多个interface。
2.在abstract class
中可以有自己的数据成员,也可以有非abstarct的成员方法,而在interface中,只能够有静态的不能被修改的数据成员(也就是必须是
static final的,不过在 interface中一般不定义数据成员),所有的成员方法都是abstract的。
3.abstract class和interface所反映出的设计理念不同。其实abstract class表示的是"is-a"关系,interface表示的是"like-a"关系。
4.实现接口的类必须实现其中的所有方法,实现抽象类的类必须实现其中的抽象方法,而非抽象方法可以不实现。抽象类中可以有非抽象方法。接口中则不能有实现方法。
5.接口中定义的变量默认是public static final 型,且必须给其初值,所以实现类中不能重新定义,也不能改变其值。
6.抽象类中的变量默认是 friendly 型,其值可以在子类中重新定义,也可以重新赋值。
7.接口中的方法默认都是 public,abstract 类型的。