Jay*_*ant 13 java oop inheritance
我有以下场景:
public class A {
private int x = 5;
public void print()
{
System.out.println(x);
}
}
public class B extends A {
private int x = 10;
/*public void print()
{
System.out.println(x);
}*/
public static void main(String[] args) {
B b = new B();
b.print();
}
}
Run Code Online (Sandbox Code Playgroud)
在执行代码时,输出为:5.
如何通过父类方法访问子类(B)变量(x)?
这可以在不覆盖print()方法的情况下完成(即在B中取消注释)吗?
[这很重要,因为在重写时我们必须再次重写print()方法的整个代码]
EDITED
更多澄清: -
(感谢您的所有时间和帮助)
Vic*_*ong 12
class A {
private int x = 5;
protected int getX() {
return x;
}
protected void setX(int x) {
this.x = x;
}
public void print() {
// getX() is used such that
// subclass overriding getX() can be reflected in print();
System.out.println(getX());
}
}
class B extends A {
public B() {
// setX(10); // perhaps set the X to 10 in constructor or in main
}
public static void main(String[] args) {
B b = new B();
b.setX(10);
b.print();
}
}
Run Code Online (Sandbox Code Playgroud)
EDITED
下面是使用抽象类和方法来解决类似场景的一般答案:
abstract class SuperA {
protected abstract Object getObj();
public void print() {
System.out.println(getObj());
}
}
class A extends SuperA {
@Override
protected Object getObj() {
// Your implementation
return null; // return what you want
}
}
class B extends A {
@Override
protected Object getObj() {
// Your implementation
return null; // return what you want
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}
Run Code Online (Sandbox Code Playgroud)
阅读完这里发布的所有答案后,我得到了我想要的东西.以下是我认为对我的问题最好的答案:
public class A {
private int x = 5;
protected int getX(){
return x;
}
public void print(){
System.out.println(getX());
}
}
public class B extends A {
private int x = 10;
protected int getX(){
return x;
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}
Run Code Online (Sandbox Code Playgroud)
设置受保护的getter并覆盖它比覆盖print()方法本身更好,因为可能有任何其他巨大的方法代替print方法,可能需要访问子类变量的值.