Search code examples
javainheritancesubclasssuperclass

Can you access sub class variable via super class in Java


Can I access my subclass variable via super class instance?

For instance I create my super class object in Main, and then I want to know the value of variable in the sub class. Is it possible to do so? Thanks.


Solution

  • If class B extends class A and you have an A object, then you can always convert it to its subclass, B in this case. Consider the following:

    A a = new A();
    B b = (B)a;
    

    afterwards, you can always reach B members via b. You can do it in an inline manner as well, via ((B)a).