class A{
int i,j;
A(int x,int y){
i=x;j=y;
}
void show(){
System.out.println("i="+i+" j="+j);
}
}
class B extends A{
int k;
B(int i,int j,int k){
super(i,j);
this.k=k;
}
void show(){
System.out.println("k="+k);
}
}
public class overridingEx{
B ob=new B(1,2,3);
ob.show(); // this will call the B's show method.
}
请告诉我有没有办法从 B 的类对象 ob 调用 A 类方法?
最佳答案
您不需要从 ob
调用 A
的 show
方法。您应该从 B
的 show
方法中调用 super.show()
。
void show(){
super.show();
System.out.println("k="+k);
}
现在,当调用 ob.show()
时,您将看到两个 show()
方法的输出:
i=1 j=2
k=3
从子类中调用 super.show()
会调用父类(super class)的 show()
方法的实现。
关于java - 我们可以从另一个类中的子类对象调用父类(super class)的重写方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18280698/