[英]Java sub class overload does not get called from super class
当对象的类型是子类(OtherClass2)并且测试函数的参数是Person2类型时,以下代码为什么会产生“超级”输出? 该方法不应该调用test(new Person2()); 调用子类的测试功能?
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)
OtherClass2
不会覆盖
public void test(Person p)
的OtherClass
。 它超载了。 但是,它仅对编译时类型为OtherClass2
变量重载(因为重载是在编译时确定的)。
因此
test(new Person2());
调用超类的方法public void test(Person p)
,因为OtherClass
没有带有签名public void test(Person2 g)
(该方法可能已被OtherClass2
的test
方法OtherClass2
)。
如果您在public void test(Person2 g)
上方添加了@Override
批注,则编译器会告诉您该方法不会覆盖超类的任何方法。
因为您在OtherClass2中的测试方法不会覆盖OtherClass中的测试(它会重载)。 你有吗
public class OtherClass2 extends OtherClass
{
public void test(Person g)
{
System.out.println("In sub");
}
public void goToThing()
{
hello();
}
}
它会按预期工作。
请参见更多详细信息以及重写和重载之间的区别 。
因为hello();
方法在OtherClass
。 您调用goToThing()
这是在OtherClass2
,那之后OtherClass2
调用hello()
方法,该方法在OtherClass
, hello()
方法调用test()
从法OtherClass
。 尝试这个:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.