Java 遗产super()的用法

Java 遗产super()的用法,java,inheritance,Java,Inheritance,我被难住了。当客户机代码(见下图)运行时,我认为super.testIt()行应该生成“it”而不是“up”,从而给出upitit作为正确答案。我将其编码并运行了它,upit是正确的答案。为什么超级方法调用会返回到子方法 public class V { public void one(){ System.out.print("it"); } public void two(){ System.out.print("go"); } public void

我被难住了。当客户机代码(见下图)运行时,我认为super.testIt()行应该生成“it”而不是“up”,从而给出upitit作为正确答案。我将其编码并运行了它,upit是正确的答案。为什么超级方法调用会返回到子方法

public class V
{
  public void one(){
     System.out.print("it");
  }
  public void two(){
     System.out.print("go");
  }
  public void testIt(){
     one();
  }  
}

public class W extends V
{
  public void one(){
     System.out.print("up");
  }
  public void two(){
     System.out.print("at");
  }
  public void testIt(){
     one();
     super.testIt();
     super.one();
  }
}

///////////////////////////////////////////////////////////////
//client code in the main of another class
W x = new W();
x.testIt();

底层类是一个W。由于多态性,它将调用W的one()方法。

因为这是虚拟方法的全部概念……我明白你的意思,但是由于每个类中都有一个one()方法,你能解释为什么调用子类的one()方法而不是父类吗?我的大多数学生都学过它,所以有一个令人信服的原因,为什么初学者会感到困惑。因为对象的类型是
W
,而
W
覆盖了
one()
,所以调用了
W.one()
。为什么人们会对此投反对票?这个问题到底有什么问题?我理解为什么对one()的调用会调用W的one()方法(duh.),但是为什么super.testIt()不调用super的one()方法,并因此输出“It”?很抱歉,这实际上也让我感到困惑…super.testIt()调用基类方法testIt(),但是,在one()的testIt()内部不会调用基类,因为派生类重写了该方法。@EJP我理解,是的。但是super.testIt()将我们引入到V中的第一个testIt()方法中,对吗?testIt()方法调用one()。这应该相当于调用this.one()。在这里,如果我错了,请纠正我,“this”指的是V?或者“this”指的是最初调用该方法的内容吗?如果是这样,我以前从未听说过Java的这个特性。但我可能会感到困惑。如果“this”指的是V,那么vone()方法应该打印出“it”。我在这里遗漏了什么?@Keara No,
super.testIt()
调用对象的
one()
方法,对象的类型为
W
。而且,
这个
指的是一个对象,而不是一个类。我明白了。感谢您的快速回复。我有足够的钱来帮助我的学生。