子类重写父类方法后的调用规则

来源:互联网 发布:网络模式怎么设置 编辑:程序博客网 时间:2024/05/17 01:02

例题:

(单选题) 下面代码的输出是什么?

  1. public class Base {  
  2.       
  3.     private String baseName= "base";  
  4.     public Base(){  
  5.         callName();  
  6.     }  
  7.       
  8.     public void callName(){  
  9.         System.out.println(baseName);  
  10.     }  
  11.       
  12.     static class Sub extends Base{  
  13.         private String baseName = "sub";  
  14.         public void callName(){  
  15.             System.out.println(baseName);  
  16.         }  
  17.     }  
  18.       
  19.     public static void main(String[] args){  
  20.         Base b = new Sub();  
  21.     }  
  22.   
  23. }  


A.null

B.sub

C.base


答案:A

为了能更好的分析代码运行过程, 做原有代码做一些变动如下:

  1. public class Base {  
  2.     private String baseName= "base";  
  3.       
  4.     public Base(){  
  5.         System.out.println("Constructor Base : " + baseName);  
  6.           
  7.         System.out.println("before Base callName() -----" );  
  8.           
  9.         callName();  
  10.           
  11.         System.out.println("after Base callName() -----" );  
  12.     }  
  13.       
  14.     public void callName(){  
  15.         System.out.println("& " + baseName);  
  16.     }  
  17.       
  18.     static class Sub extends Base{  
  19.         private String baseName = "sub";  
  20.           
  21.         public Sub(){  
  22.             System.out.println("Constructor Sub : " + baseName);  
  23.         }  
  24.           
  25.         @Override  
  26.         public void callName(){  
  27.             System.out.println("# " + baseName);  
  28.         }  
  29.     }  
  30.       
  31.     public static void main(String[] args){  
  32.         new Sub();  
  33.     }  
  34.   
  35. }  


此时 main 方法内 new Sub();

输出结果:

  1. Constructor Base : base  
  2. before Base callName() -----  
  3. # null  
  4. after Base callName() -----  
  5. Constructor Sub : sub  


再将main方法做如下变动:

  1. public static void main(String[] args){  
  2.       
  3.     Base b = new Sub();  
  4.       
  5.     b.callName();  
  6. }  

输出结果

  1. Constructor Base : base  
  2. before Base callName() -----  
  3. # null  
  4. after Base callName() -----  
  5. Constructor Sub : sub  
  6. # sub   


综上所述, 此时运行的是子类Sub的callName() 方法, 

new Sub();在创造派生类的过程中首先创建基类对象,然后才能创建派生类。
创建基类即默认调用Base()方法,在方法中调用callName()方法,由于派生类中存在此方法,则被调用的callName()方法是派生类中的方法,此时派生类还未构造,所以变量baseName的值为null


先成员变量再构造方法,先父类再子类
多态表现:有同名方法执行子类的

执行 Base b = new Sub();时,由于多态 b编译时表现为Base类特性,运行时表现为Sub类特性
Base b = new Sub();不管是哪种状态都会调用Base构造器执行 callName()方法;
执行方法时,由于多态表现为子类特性,所以会先在子类是否有 callName();
而此时子类尚未初始化(执行完父类构造器后才会开始执行子类),如果有 就 执行(此时, 因为还没有调用子类构造函数, 所以子类的 baseName 输出为 null),没有再去父类寻找。
阅读全文
0 0
原创粉丝点击