首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

关于继承的一些有关问题

2012-01-14 
关于继承的一些问题3.7Whatisdisplayedwhenthefollowingpieceofcodeiscompiledandexecuted?classTest{publ

关于继承的一些问题
3.7   What   is   displayed   when   the   following   piece   of   code   is   compiled   and   executed?
class   Test   {
      public   static   void   main(String   []   args)   {
                      Base   b   =   new   Subclass();
                      System.out.println(b.x);
                      System.out.println(b.method());
              }
}
class   Base   {
      int   x   =   2;
      int   method(){
                      return   x;
      }
}
class   Subclass   extends   Base   {
      int   x   =   3;
      int   method()   {
      return   x;
      }
}


希望能够详细说这道题。把知识点说道

[解决办法]
输出2,3

因为Java中类的成员变量不会被覆盖,所以
Base b = new Subclass();
System.out.println(b.x);//这样得到的是Base 类中的x值
System.out.println(b.method());//方法会被覆盖,所以调用的是Subclass的method方法
而在Subclass中return x的x实际上是Subclass中的x而不是Base的

热点排行