Java编程思想读书笔记_第8章

覆盖私有方法

 1 class Father {
 2     private void f() { System.out.println("Father::f()"); }
 3     public static void main(String[] args) {
 4         Father father = new Son();
 5         father.f(); //输出:Father::f()
 6     }
 7 }
 8 
 9 class Son extends Father {
10     public void f() { System.out.println("Son::f()"); }
11     public static void main(String[] args) {
12         Son son = new Son();
13         son.f(); //输出:Son::f()
14     }
15 }

上面例子中由于Father的f是私有的,所以在Father的main方法中对f的调用是静态绑定的。

如果把f定义为public的,则在Father中对f的调用将是动态绑定的。

 

域与静态方法

 1 class Father {
 2     public int i = 0;
 3     public int get() { return i; }
 4 }
 5 
 6 class Son extends Father {
 7     public int i = 1;
 8     public int get() { return i; }
 9     public int get_super() { return super.i; }
10 }
11 
12 class Test {
13     public static void main(String[] args) {
14         Father f = new Son();
15         System.out.println(f.i); //0
16         System.out.println(f.get());//1
17         Son s = new Son();
18         System.out.println(s.i);//1
19         System.out.println(s.get());//1
20         System.out.println(s.get_super());//0
21         Son s1 = (Son)f;
22         System.out.println(s1.i);//1
23         System.out.println(s1.get());//1
24         System.out.println(s1.get_super());//0
25     }
26 }

对于成员函数的访问是没有多态的,子类型和父类型中的i是不同的存储空间。使用父指针访问的时候使用的父的空间,使用子指针访问的时候使用的是子的空间。

 

在构造函数中调用的函数如果是可以动态绑定的,并且在子类中被继承了,那么就会调用子类的方法

 1 class Father {
 2     void draw() { System.out.println("Father::draw"); }
 3     Father() { draw(); }
 4 }
 5 
 6 class Son extends Father {
 7     int i = 1;
 8     void draw() { System.out.println("Son::draw: " + i); }
 9 }
10 
11 class Test {
12     public static void main(String[] args) {
13         new Son(); //Son::draw: 0
14     }
15 }

如果把Father中的draw定义为private的,那么在Test中的输出就是Father::draw

 

 

posted @ 2017-07-16 16:55  Ren.Yu  阅读(251)  评论(0编辑  收藏  举报