日期:2014-05-20  浏览次数:20734 次

java简单问题
23.   What   will   happen   when   you   attempt   to   compile   and   run   the   following   code?
class   Base{
int   i   =   99;
public   void   amethod(){
              System.out.println( "Base.amethod() ");
        }
        Base(){
          amethod();
          }
}
public   class   Derived   extends   Base{
int   i   =   -1;
public   static   void   main(String   argv[]){
          Base   b   =   new   Derived();
              System.out.println(b.i);
              b.amethod();
      }
      public   void   amethod(){
              System.out.println( "Derived.amethod() ");
      }
}
A.   Derived.amethod()
-1
Derived.amethod()
B.   Derived.amethod()
    99
    Derived.amethod()
C.   99
D.   99
    Derived.amethod()
E.   compile   time   error.
B   is   correct.   The   reason   is   that   this   code   creates   an   instance   of   the   Derived   class   but   assigns   it   to   a   reference   of   a   the   Base   class.   In   this   situation   a   reference   to   any   of   the   fields   such   as   i   will   refer   to   the   value   in   the   Base   class,   but   a   call   to   a   method   will   refer   to   the   method   in   the   class   type   rather   than   its   reference   handle.   But   note   that   if   the   amethod()   was   not   present   in   the   base   class   then   compilation   error   would   be   reported   as   at   compile   time,   when   compiler   sees   the   statement   like   b.amethod(),   it   checks   if   the   method   is   present   in   the   base   class   or   not.   Only   at   the   run   time   it   decides   to   call   the   method   from   the   derived   class.

这道题看的我有点不懂,希望能够详细说明,把知识点说一下~~谢谢

------解决方案--------------------
这道题应该是用到的知识点应该有 继承 ,构造方法的调用, 方法的重写
Derived 类 是 Base类的子类
子类构造方法可以调用父类的构造方法,父类构造方法的调用总是先于子类构造方法的掉用
说白了 就是实例话子类对象的时候 先掉用了父类的构造方法,然后才调用子类的构造方法
B是正确的
------解决方案--------------------
主要是编译期间和运行期间的问题
Base b = new Derived();
简单点说就是在编译期间选择的是Base,此时b.i就有值了,属于Base类的 99
第1个输出 调用的是Base()方法,由于amethod()被重写了,所以调用的是子类的方法,b.amethod();
第2个输出b.amethod()很明显是子类的amethod()
------解决方案--------------------
Base b = new Derived();优先调用父类的构造方法 Base(){amethod();}
而方法被子类Derived的amethod()覆盖了,所以调用
public void amethod(){
System.out.println( "Derived.amethod() ");