Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading