Java继承和隐藏的公共字段 [英] Java inheritance and hidden public fields
问题描述
为了模拟一些看起来像这样的自动生成的类,我制作了一个小的jUnit测试类来模拟继承和隐藏字段.
To simulate some auto-generated classes which looks like this, I made a small jUnit test class to simulate inheritance and hidden fields.
public class ClassDerivationTest {
@Test
public void testChild() {
ChildClass child = new ChildClass();
// Implicit boolean as it is hiding the super value
child.value = true;
// one way to update the parent value
// child.setParentVal("true");
// child.super.value = "test";
}
public class ChildClass extends ParentClass {
public boolean value;
}
public class ParentClass {
public String name;
public String value;
}
}
我的问题是:是否可以通过类似的方式来分配超类value
字段的任何简短方法:
My question is: is there any short way to assign the super class value
field in a similar way like this:
child.super.value = "test";
而不是在ChildClass中创建特定的设置器:
instead than creating a specific setter in the ChildClass:
// Imagine this method is not existing for the question
public void setParentVal(String val) {
super.value = val;
}
我正在使用Java 7,我想知道是否可以在不修改ChildClass
或ParentClass
的情况下进行修改(就像它可能是自动生成的代码一样).
I am using Java 7, and I am wondering if it would be possible without modifying the ChildClass
nor the ParentClass
(Like it could be auto-generated code).
更新:
我知道您有几种方法可以通过
a)根据乔恩的答案进行投射:((ParentClass) child).value = "test";
,但效果不是很好
b)尽可能实例化超类:ParentClass myInstance = new ChildClass();
代码myInstance.value
将引用ParentClass中的字段
UPDATE:
I know you there are several ways to manage this by
a) Casting according to Jon's answers: ((ParentClass) child).value = "test";
but not very well
b) Instanciate the super class like this (as much as possible): ParentClass myInstance = new ChildClass();
The code myInstance.value
will refer to the field in ParentClass
但是我想更加关注Java 8的新功能. 例如,是否可以使用lambda或Java 8的另一个新功能来解决此问题?
But I wanted to be more focused on the new features of Java 8. For example is it possible to resolve this with a lambda, or another new feature of Java 8?
推荐答案
好吧,您可以强制转换child
来使编译器相对于ParentClass
而不是ChildClass
来解析字段value
:
Well you can just cast child
to make the compiler resolve the field value
with respect to ParentClass
instead of ChildClass
:
((ParentClass) child).value = "test";
但坦率地说,我会:a)避免使用非私有字段; b)避免有意识地给同名的超类和子类字段.
But frankly I would a) avoid non-private fields; b) avoid knowingly giving superclasses and subclasses fields with the same name.
与您的评论相反,子类字段不会覆盖"超类字段-它会将其隐藏.
Contrary to your comment, the subclass field doesn't "override" the superclass field - it hides it.
这篇关于Java继承和隐藏的公共字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!