9.1 抽象类和抽象方法
抽象类可以不含有任何抽象方法;含有抽象方法的类必须被声明为abstract。
9.2 接口
接口中可以含有域,隐含为static final(实际上也是Public的)。
来看一下含有abstract class和interaface的继承体系的加载和初始化顺序。
以下几条在书中没有讲到,中Java 6下试出来的:
- Interface中不能含有初始化块,标准的编译错误提示:The interface xxx cannot define an initinalizer.
- Interface中不能定义构造器。(因为interface中没有构造器和初始化块,所以interface中的域不可以为blank final的。)
- Abstract class的初始化与构造器调用与普通class没有区别
- Interface不参与初始化和构造器调用。
注意下面的代码片段,IBase是一个Interface,它的public(static final)域i1直到被使用的时候才会执行初始化(直到i1被使用的时候IBase才被加载)。
1 import static java.lang.System.out; 2 class Indicator { 3 Indicator(String name){ 4 out.println(name); 5 } 6 } 7 8 interface IBase { 9 public static final Indicator i1 = new Indicator("i1"); 10 /* An interface cannot have initializer and constructor. 11 Indicator i2; 12 { 13 i2 = new Indicator("i2"); 14 } 15 IBase() {} 16 */ 17 void f(); 18 } 19 20 abstract class Base implements IBase{ 21 private static Indicator i3 = new Indicator("i3"); 22 private Indicator i4 = new Indicator("i4"); 23 private Indicator i5; 24 { 25 i5 = new Indicator("i5"); 26 } 27 private Indicator i6; 28 Base(){ 29 i6 = new Indicator("i6"); 30 } 31 } 32 33 public class Test extends Base { 34 public void f(){ 35 out.println(this.i1); 36 } 37 public static void main(String args[]){ 38 new Test().f(); 39 } 40 }/* 41 i3 42 i4 43 i5 44 i6 45 i1 46 Indicator@ca0b6 47 */