Kushal Mondal
Kushal Mondal

Reputation: 111

Cannot access method from superclass when subclass instantiated using Object variable

I was practising inheritance and had these classes where Bite extends the Gulp class.

public class Gulp {
    public void method2() {
        System.out.println("Gulp 2");
        method3();
    }

    public void method3() {
        System.out.println("Gulp 3");
    }
}

public class Bite extends Gulp {
    public void method1() {
        System.out.println("Bite 1");
    }

    public void method3() {
        System.out.println("Bite 3");
    }
}

I am trying to invoke the method method2() by creating objects of Bite class(using three different kind of references: Object,Bite and Gulp) as below:

public class Main {
    public static void main(String[] args) {
        Object varObj = new Bite();
        Bite varBite = new Bite();
        Gulp varGulp = new Bite();

        if(varBite.getClass() == Bite.class) 
            System.out.println("Bite class");

        if(varObj.getClass() == Bite.class) 
            System.out.println("Also Bite class");

        varBite.method2();
        //prints what is expected

        varObj.method2();
        //throws compilation error -- cannot find method2()

        varGulp.method2();
        //prints what is expected
    }
}

I am getting error when the reference variable is type of Object. It says, it cant find the symbol although the varObject.getClass() returns Bite.class. Could anyone please explain..

Upvotes: 0

Views: 1821

Answers (1)

ernest_k
ernest_k

Reputation: 45309

The compiler won't let you call methods specific to Bite if you declared the variable as of type Object.

You have two options: Either declare the objects as Bite, like varBite. Or cast the Object variable to Bite:

((Bite)varObj).method2();

Upvotes: 2

Related Questions