class A {
void test() {
}
}
class B extends A {
void test() {
}
public static void main(String[] args)
{
B b=new B();
//insert code here
}
}
Run Code Online (Sandbox Code Playgroud)
如何test为B 类的对象b调用A类的方法?特别是对象b
Jon*_*eet 14
你不能从B 外面调用它...但在 B中你可以称之为:
super.test();
Run Code Online (Sandbox Code Playgroud)
这可以从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");
}
Run Code Online (Sandbox Code Playgroud)
请注意,@Override它告诉你真正的编译器注释也意味着覆盖的方法.(除此之外,如果方法名称中有拼写错误,这将有助于您快速找到它.)
你无法从外部B调用它的原因是B 覆盖了方法... 覆盖的目的是替换原始行为.例如,在带参数的方法中,B可能希望在调用超类实现或执行其他操作之前对参数执行某些操作(根据其自己的规则对其进行验证).如果外部代码只能调用A的版本,那将违反B的预期(和封装).
| 归档时间: |
|
| 查看次数: |
1507 次 |
| 最近记录: |