Use Private Members from Base Class

  最近看了一段代码:在导出类中调用继承自基类的某个public函数,该函数中对基类中的private数据成员

进行了赋值并将结果打印。看到程序的运行结果后,顿时感觉自己之前(我之前的理解这里就不说明了)对于

基类/导出类中私有数据成员的理解并不是很准确。所以写了下面的这个程序,进行简单的验证并加深理解:

class Insect {
    private int i = 9;
    Insect() {
        System.out.println("Insect.");
    }
    private int x1 = printInit("Insect.x1 initialized");
    //在导出类中不能访问基类的private成员函数print(),但可以访问printInit()(通过printInit()来访问private成员函数print()).
    int printInit(String s) {
        System.out.println(this.toString());
        this.print(s);
        return 47;
    }
    private void print(String s){
        System.out.println(s);
    }
    //在导出类中不能访问基类的private数据成员i,但可以访问usePrivateVar()(通过usePrivateVar()来访问private数据成员).
    public void usePrivateVar(){
        System.out.println(this.toString());
        System.out.println("i = " + this.i);
    }
}

public class beetle extends Insect {
    private int x2;
    private int k = printInit("beetle.k initialized");
    {
        x2 = printInit("beetle.x2 initialized");
    }
    public beetle() {
        System.out.println("beetle.");
    }
    public static void main(String[] args) {
        beetle b = new beetle();
        b.usePrivateVar();
    }
}

 Output:

    beetle@1db9742            -- NOTE: NOT Insect.
    Insect.x1 initialized
    Insect.
    beetle@1db9742
    beetle.k initialized
    beetle@1db9742
    beetle.x2 initialized
    beetle.
    beetle@1db9742
    i = 9

  

  此外,注意beetle.x2 initialized 和 beetle.k initialized 的顺序. 与两个变量声明的顺序无关,而是

由printInit()语句的调用顺序(两个变量初始化的顺序)决定。

posted @ 2014-06-01 22:09  XiaoweiLiu  阅读(354)  评论(0编辑  收藏  举报