Search code examples
javaclassvariablessubclasssuperclass

How to access subclass variable from superclass?


Say I have 2 classes, A and B. B is a subclass of A, and B has a variable specific to that class, example:

private class A{}
private class B extends A{int x = 5;}

And I store a B as an A,

A instB = new B();

How do I access x in B? In this example it's a constant, but in my program it isn't, so i need some way to access the variable itself.


Solution

  • If you really need to store the object as 'A' instead of 'B', then I believe your only answer would be to cast 'instB' to back to 'B' for you to access that member.

    int member = ((B)instB).x;
    

    But something about that software design just doesn't seem right if you need to access child class members from the superclass.