简体   繁体   中英

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.

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?

Thanks!

Your code doesn't compile as said by Jon Skeet because you're trying to access a field of your B's field.

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.

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.


Solution

System.out.println(((X)b1.member).strX);

As you see, first we cast b1.member to X and then we call the strX field.

And if you want to be sure that b1.member is an instance of X , use an if test like this

if (b1.member instanceof X) System.out.println(((X)b1.member).strX);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM