接口和抽象类

1. 抽象类的实例化

 1 package interfaces;
 2 abstract class BaseWithPrint {
 3   public BaseWithPrint() { print(); }
 4   public abstract void print();
 5 }

 6 class DerivedWithPrint extends BaseWithPrint {
 7   int i = 47;
 8   public void print() {
 9     System.out.println("i = " + i);
10   }
11 }

12 public class E03_Initialization {
13   public static void main(String args[]) {
14   DerivedWithPrint dp = new DerivedWithPrint();
15   dp.print();
16   }
17 } 

/* Output:
18 i = 0
19 i = 47

 执行顺序:由于DerivedWithPrint继承自BaseWithPrint,在实例化的过程中,先实例化了基类,基类的构造函数中调用了print,值得注意的是,这边基类中调用的是子类的print函数去执行,然后再执行了dp.print().

抽象类初始化顺序:父类静态块初始化---->子类静态块初始化---->父类非静态块初始化---->父类构造方法---->子类非静态块初始化---->子类构造方法(先静后动,先父后子)。

抽象类实际上是定义了一个标准和规范,等着他的子类们去实现,譬如动物这个抽象类里定义了一个发出声音的抽象方法,它就定义了一个规则,那就是谁要是动物类的子类,谁就要去实现这个抽象方法。
• 抽象类可以继承(extends)类,可以继承(extends)抽象类,可以继承(implements)接口。
• 接口只能继承(extends)接口。

2. Q:为什么接口中只能有static和final的域?为什么抽象类中只要有一个方法是abstract的,这个类就必须是abstract的?

   A: 其实两个问题都是因为实例化。

  1.

Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.

  2. 这是因为抽象方法没有定义方法的实现部分,如果不声明为抽象类,这个类将可以生成对象,这时当用户调用抽象方法时,程序就不知道如何处理了。

posted on 2012-09-05 16:13  clara_babybear  阅读(299)  评论(0编辑  收藏  举报