简体   繁体   中英

Java sub class overload does not get called from super class

Why does the following code produce the output "in super", when the object's type is the sub class (OtherClass2) and the argument to the test function is of type Person2? Shouldn't the method call test(new Person2()); call the sub class's test function?

public class HelloWorld
{
  public static void main(String[] args)
  {
    OtherClass2 s = new OtherClass2();


    s.goToThing();
  }
}

public class Person
{

}

public class Person2 extends Person
{

}

public class OtherClass
{
  public void hello()
  {
    test(new Person2());
  }

  public void test(Person p)
  {
    System.out.println("in super");
  }
}

public class OtherClass2 extends OtherClass
{
  public void test(Person2 g)
  {
    System.out.println("In sub");
  }

  public void goToThing()
  {
    hello();
  }
}
public void test(Person2 g)

of OtherClass2 does not override

public void test(Person p)

of OtherClass . It overloads it. However, it only overloads it for variables whose compile time type is OtherClass2 (since overloading is determined at compile time).

Therefore

test(new Person2());

invokes the method public void test(Person p) of the super class, since OtherClass has no method with the signature public void test(Person2 g) (which could have been overridden by the test method of OtherClass2 ).

Had you added an @Override annotation above public void test(Person2 g) , the compiler would have told you that this method is not overriding any method of the super class.

Because your test method in OtherClass2 does not override test in OtherClass (it overloads). Would you have

public class OtherClass2 extends OtherClass
{
  public void test(Person g)
  {
    System.out.println("In sub");
  }

  public void goToThing()
  {
    hello();
  }
}

it would work as expected.

See some further details and differences between overriding and overloading .

Because hello(); method is in OtherClass . You calls goToThing() which is in OtherClass2 , after that OtherClass2 calls hello() method which in OtherClass , hello() method calls test() method from OtherClass . Try this:

public class OtherClass2 extends OtherClass
{
    public void hello()
    {
        test(new Person2());
    }
  public void test(Person2 g)
  {
    System.out.println("In sub");
  }

  public void goToThing()
  {
    hello();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM