Reputation: 23
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.
Upvotes: 2
Views: 84
Reputation: 21
This concept is linked with Runtime Polymorphism. Here, the reference variable "b" belongs to the parent class (Programmer) and object belongs to the child class (Author).
Now, reference variable "b" is pointing to the child (Author) class.
There are two definition for print() method one belongs to the Programmer and another belongs to the Author class.The determination of the method to be called is based on the object being referred to by the reference variable. The process in which call to a function will resolve at run time.
So whenever you call b.print(), you'll be getting output as:
Upvotes: 0
Reputation: 11
When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time.
It is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.
Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the method are executed. That's why you are getting output : Author - Mala Gupta
Upvotes: 0
Reputation: 3232
Programmer
is the parent class and Author
is the child of Programmer
. Parent class contain the reference of child class object but you can only call those methods which are in Parent class.
In Programmer b
actually there is a reference of Author
class. Thats why it called the Author
class function. its called Polymorphism
.
Upvotes: 0
Reputation: 4799
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
.
Upvotes: 1