继承3个班级

时间:2016-02-15 16:39:51

标签: java inheritance

代码:

    class Super {
      void print(Super a) {
         System.out.print("Super");
      }
    }
    class Base extends Super{
      void print(Base a) {
         System.out.print("Base");
      }
    }
    class Derived extends Base{
      void print(Derived a) {
         System.out.print("Derived");
      }
    }
    class Test {
      public static void main(String args[]){
        Super a1= new Super();
        Super b1= new Base();
        Base c1= new Derived();
        a1.print(new Base());
        b1.print(new Derived());
        c1.print(new Derived());
      }
    }

输出:“SuperSuperBase”

它是如何工作的,请解释一下?我明白不可能给出简短的答案,但是......理解起来很难

1 个答案:

答案 0 :(得分:1)

  

输出:“SuperSuperBase”

    Super a1= new Super();
    a1.print(new Base());

Super类对象是w.r.t Super创建的。 <{1}}类的print()方法将被调用。

Super

此处 Super b1= new Base(); b1.print(new Derived()); 是类型b1类的引用。因此,Super类的print()方法将被调用。

Super

此处 Base c1= new Derived(); c1.print(new Derived()); 是类型c1类的引用。因此,Base类的print()方法将被调用。