在java中可以访问父类中的子类变量吗?
你必须通过设计或使用反射的发现来了解孩子 这个例子取决于一个包是公共的而不是私有的在java中可以访问父类中的子类变量吗?,java,Java,你必须通过设计或使用反射的发现来了解孩子 这个例子取决于一个包是公共的而不是私有的 class Parent { //need to access variable of child class } class Child extends Parent { int a=10; } 如果你真的必须这样做,你需要做的是试着用反射来获得场,并抓住场没有被找到的可能性。尝试以下方法: public int getChildA() { int a = 0; if (this insta
class Parent
{ //need to access variable of child class
}
class Child extends Parent
{ int a=10;
}
如果你真的必须这样做,你需要做的是试着用反射来获得场,并抓住场没有被找到的可能性。尝试以下方法:
public int getChildA() {
int a = 0;
if (this instanceof Child) {
a = ((Child)this).a;
}
return a;
}
输出为10,但从设计角度来看,这仍然是一个非常糟糕的想法。我还必须为演示制作类,但您可以毫无问题地将它们更改回去。不。如果没有大量的思考,这是不可能的,而且通常是一个坏主意。家长永远不应该对子类有任何依赖性,甚至不应该了解子类。句号。这清楚地表明您的设计是错误的。从技术角度来看,我认为这个问题是一个挑战,从设计角度来看……哦,男孩:假设您正在父类中创建方法,该方法将由子类继承,并且它应该能够使用该子类中的某些字段。为什么不首先在父类中声明这样的文件呢?若你们不能,那个么若你们的方法将被并没有这个字段的子类继承,那个么你们的方法应该如何反应呢?
static class Parent
{
public int getChildA(){
try {
Class clazz = Child.class;
Field f = clazz.getDeclaredField("a");
if(!f.isAccessible())
f.setAccessible(true);
return f.getInt(this);
} catch (NoSuchFieldException ex) {
//the parent is not an instance of the child
} catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SOtests.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
}
static class Child extends Parent
{
int a=10;
}
public static void main(String[] args) {
Child c = new Child();
Parent p = (Parent) c;
System.out.println(p.getChildA());
}