class A {
void test() {
}
}
class B extends A {
void test() {
}
public static void main(String[] args)
{
B b=new B();
//insert code here
}
}
如何为 Btest
类的对象b调用 A 类的方法?专门针对对象 b
class A {
void test() {
}
}
class B extends A {
void test() {
}
public static void main(String[] args)
{
B b=new B();
//insert code here
}
}
如何为 Btest
类的对象b调用 A 类的方法?专门针对对象 b
您不能从B外部调用它...但在B 内部您可以将其称为:
super.test();
这可以从 B 中的任何代码完成 - 它不必在test()
方法本身中。例如:
public void foo() {
// Call the superclass implementation directly - no logging
super.test();
}
@Override void test() {
System.out.println("About to call super.test()");
super.test();
System.out.println("Call to super.test() complete");
}
请注意@Override
告诉编译器您确实是要覆盖方法的注释。(除此之外,如果您在方法名称中有拼写错误,这将帮助您快速找到它。)
您不能从 B 外部调用它的原因是 B覆盖了该方法......覆盖的目的是替换原始行为。例如,在带有参数的方法中,B 可能希望在调用超类实现或执行其他操作之前对参数执行某些操作(根据自己的规则对其进行验证)。如果外部代码只能调用 A 的版本,那将违反 B 的期望(和封装)。
类本身是错误的。定义类名时不应添加括号。您可以在B 类super.test()
的方法中使用对象类型转换或调用test
class A
{
test()
{}
}
class B extends A
{
test()
{
super.test() // calls the test() method of base class
}
}
B b=new B();
这可用于使用派生类对象调用基类方法。
b.super.test()