我的背景是 C++,我们可以使用子类对象访问父类的公共(public)字段。示例:
#include <iostream>
class A{
public:
void show(){
std::cout << "A";
}
};
class B:public A{
public:
void show(){
std::cout << "B";
}
};
int main(){
B obj;
obj.A::show(); // it will print A.
}
我如何在 Java 继承中做同样的事情?
public class Serial {
public void show(){
System.out.println("Serial");
}
}
public class Testing extends Serial
{
@Override
public void show(){
System.out.println("Testing");
}
public static void main(String[] args){
Testing obj=new Testing();
obj.show(); // it print Testing but how to Print Serial?
}
}
我还有另一个关于覆盖的问题,但由于 Stackoverflow 规则,我将作为单独的问题提出。
那么,打印/访问带有子类对象引用的 Java 父类方法的语法应该是什么?
我试过。 obj.super.show();
等但不起作用。
最佳答案
super
只能在类里面使用。不在它之外。
因为你 ovveride,你不能直接调用 super 方法。
你只能做
obj.show();
如果你仍然想调用 super 方法,你可以将你的方法修改为
@Override
public void show(){
super.show();
System.out.println("Testing");
}
更新:
来到 Parent 和 Child 覆盖返回类型,
这篇文章可能有帮助
关于java - 使用子对象 Java 访问父字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32738342/