Using a variable of a superclass to access an object of a derived class

Java User :

i'm trying in this question to resolve this problem. When referencing a child class using a parent class reference, we call the parent class's methods.

class Programmer {
    void print() {
        System.out.println("Programmer - Mala Gupta");
    }
}

class Author extends Programmer {
    void print() {
        System.out.println("Author - Mala Gupta");
    }
}

class TestEJava {
    Programmer a = new Programmer();
    Programmer b = new Author();
    b.print();
}

Following this code, I get the output like this 'Author - Mala Gupta'; despite that I should get the parent's method executed. Can you explain to me what's happening behind the scenes.

Pavel Smirnov :

You should not get 'Programmer - Mala Gupta' output, because you're creating the Author object:

new Author();

Programmer in this case is just a reference to the object. And this reference can point at any object of Programmer and its subclasses.

But, when you invoke a method, you invoke it on the object pointed by the reference. And that's Author.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158599&siteId=1