[英]How do I use different classes as member for one class?
I have a superclass A, two classes X,Y which inheriting from A and another class B where I will use X,Y as member. 我有一个超类A,两个继承自A的类X,Y和另一个将使用X,Y作为成员的类B。
public class A {
public String strA;
}
public class X extends A {
public String strX;
}
public class Y extends A {
public String strY;
}
public class B {
public A member;
public B(A member) {
this.member=member;
}
}
public static void main() {
X x = new X();
Y y = new Y();
B b1 = new B(x);
B b2 = new B(y);
System.out.println(b1.strA); //works
System.out.println(b1.strX); //does not work!
System.out.println(b2.strA); //works
System.out.println(b2.strX); //does not work!
}
How can I solve this problem? 我怎么解决这个问题?
My approach would be that I use the datatype for the member in B as a placeholder? 我的方法是将B中的成员的数据类型用作占位符?
Thanks! 谢谢!
Your code doesn't compile as said by Jon Skeet because you're trying to access a field of your B's field. 您的代码无法像Jon Skeet所说的那样进行编译,因为您试图访问B字段中的一个字段。
To compile, the code would have been 要进行编译,代码应该是
System.out.println(b1.member.strA); //works
What you'll have to do here to use the fields from the inherited instances is explicitely cast your member
reference. 要使用继承的实例中的字段,在此处必须执行的操作明确地强制转换了
member
引用。
If you're using a reference to the motherclass, it will only show you the fields accessible from the motherclass. 如果您使用对母类的引用,它将仅显示从母类可访问的字段。
In this case, only strA
is accessible with an A
reference. 在这种情况下,只能通过
A
引用访问strA
。
System.out.println(((X)b1.member).strX);
As you see, first we cast b1.member
to X
and then we call the strX
field. 如您所见,首先将
b1.member
为X
,然后将其strX
字段。
And if you want to be sure that b1.member
is an instance of X
, use an if test like this 而且,如果要确保
b1.member
是X
的实例,请使用类似if的测试
if (b1.member instanceof X) System.out.println(((X)b1.member).strX);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.