Search code examples
javainheritancereferencesubclasssuperclass

Accessing a randomly-assigned object


Given the following:

class ClassA

class ClassA1 extends ClassA
class ClassA2 extends ClassA
class ClassA3 extends ClassA

ClassA1 a1 = new ClassA1()
ClassA2 a2 = new ClassA2()
ClassA3 a3 = new ClassA3()

ClassA a = either a1, a2, or a3 (programmed to be randomly chosen by JVM)

If the reference to the subclass object (either 'a1', 'a2', or 'a3') is only assigned to the superclass reference variable 'a' at runtime, how can I write an 'if' statement that implements: if 'a' refers to a1, access a specified field of a1 (which is not inherited from a)? Any assistance on this would be appreciated.


Solution

  • Use the instanceof operator and casting.

    if (a instanceof ClassA1) {
        ((ClassA1) a).someMethodThatsOnlyInA1();
    }