我有以下情况:
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(); } }
在执行代码时,输出为:5.
这可以在不覆盖print()方法的情况下(即在B中取消注释)吗?
[这很重要,因为在重写时,我们将不得不重新编写print()方法的整个代码)
EDITED
更多澄清:
>问题的动机是从父类方法中使用子类私有变量的值.这不需要更改父类私有变量的值才能实现所需的结果.
>然而,这里发布的答案使我得到了我所期望的答案,我已经在下面发贴了.
(感谢所有的时间和帮助)
解决方法
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(); } }
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(); } }