Can you access subclass variables with a superclass object?

In the following code, I pass the testmethod () method an instance of subclass A called B

Unfortunately, the signature for the method accepts superclass A, not subclass B, and I cannot change this signature because it refers to many classes.

Is there a way (without changing the signature of testmethod ()) that I can access the var2 variable from inside the testmethod () method, which 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;
        }
+4
source share
4 answers

You can do this:

if(a2 instanceof B)
  System.out.println("in testmeth->" + ((B) a2).getVar2() );
else
  System.out.println("in testmeth->" + a2.getVar1() );
+2
source

You can downcast , but this is usually not a good practice.

So it will be

System.out.println("in testmeth->" + ((B) a2).getVar2() );

: a2 instanceof B, ClassCastException

+3

, . :

public class test5  {

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

    public static void testmethod(A a2 ) {
        System.out.println("in testmeth_a->" + a2.getVar1() );
    }

    public static void testmethod(B b2 ) {
        System.out.println("in testmeth_b->" + b2.getVar2() );
    }
}

NB. , . . .

+2

, , A , B ( ) getVar2(). , getVar2 A:

abstract class A {
   int var1 = 2;

    public int getVar1() {
        return var1;
    }
    public abstract int getVar2();
}
0

Source: https://habr.com/ru/post/1624999/


All Articles