第9章 接口

9.1 抽象类和抽象方法

抽象类可以不含有任何抽象方法;含有抽象方法的类必须被声明为abstract。

9.2 接口

接口中可以含有域,隐含为static final(实际上也是Public的)。

来看一下含有abstract class和interaface的继承体系的加载和初始化顺序。

以下几条在书中没有讲到,中Java 6下试出来的:

  1. Interface中不能含有初始化块,标准的编译错误提示:The interface xxx cannot define an initinalizer.
  2. Interface中不能定义构造器。(因为interface中没有构造器和初始化块,所以interface中的域不可以为blank final的。
  3. Abstract class的初始化与构造器调用与普通class没有区别
  4. 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 */

 

转载于:https://www.cnblogs.com/peter9606/archive/2013/05/02/ThinkingInJava_Chapter09.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值