Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you access subclass variables with object of superclass?

In the following code, I pass to the method "testmethod() an instantiation of a subclass of A, named B

Unfortunately, the signature for the method accepts the superclass A not the subclass B and I can't change that signature since it's referred by many classes.

Is there a way (without changing the signature of testmethod()) that I can access the var2 variable from within testmethod() that is part of the object that was passed to testmethod?

    public class test5  {

        public static void main(String args[]){
            B b = new B();
            testmethod(b);
        }

        public static void testmethod(A a2 ) {
            System.out.println("in testmeth->" + a2.getVar1() );   // WORKS
            System.out.println("in testmeth->" + a2.getVar2() );   // DOESNT WORK
        }
    }

    class A  {
        int var1 = 2;

        public int getVar1() {
            return var1;
        }
    }

    class B extends A {
        int var2 = 8;

        public int getVar2() {
            return var2;
        }
like image 941
Sarta Avatar asked Jan 19 '16 17:01

Sarta


1 Answers

You can cast like this:

if(a2 instanceof B)
  System.out.println("in testmeth->" + ((B) a2).getVar2() );
else
  System.out.println("in testmeth->" + a2.getVar1() );
like image 119
CMPS Avatar answered Sep 28 '22 04:09

CMPS