This question is taken from an AP Computer Science practice test.
public class Bird
{
public void act()
{
System.out.print("fly");
makeNoise();
}
public void makeNoise()
{
System.out.print("chirp");
}
}
public class Dove extends Bird
{
public void act()
{
super.act();
System.out.print("waddle");
}
public void makeNoise()
{
super.makeNoise();
System.out.print("coo");
}
}
Suppose the following declaration appears in a class other than Bird or Dove:
Bird pigeon = new Dove();
What is printed as a result of the call pigeon.act()
?
I thought the answer would be "fly chirp", but the textbook says that the answer is "fly chirp coo waddle". I thought that 'pigeon' could only access methods available in Bird? I was under the impression that, if the user wanted to access methods in Dove, 'pigeon' would have to be cast to Dove.
Would Bird pigeon = new Bird();
give the same output? How about Dove pigeon = new Dove();
?
From your question "I thought that 'pigeon' could only access methods available in Bird? I was under the impression that, if the user wanted to access methods in Dove, 'pigeon' would have to be cast to Dove." This is actually true.
Lets try to find the mssing link in the understanding.
When we have code like Bird pigeon = new Dove();
where Dove
extends Bird
we have actual object of Dove
and reference type is of Bird
. As the object is of Dove
so it has the methods, both inherited from super class as well as the ones which are added.
Another important point is all the overriden
methods have only one instance. Its Overriden meaning the behavior of the same method has been modified, its not an additional separate method. There is only one copy of inherited method not both. Its the overloaded methods which are separate, just the names are same but signature is different. This is the reason you get the behaviour of Dove when you invoke any overriden method.
This one is simple super
, using it a sub class can access the accessible (visible) entities (instance properties and methods) of its super class. If a sub class uses super
keyword to invoke a method then its the method of the parent class which gets invoked. But again this can be considered that the author of the sub class did it intentionally. Once the class is written and Objects of such class is created then on the object using .
(dot operator) users can only invoke whats there in the object. If any method has used super
keyword its part of the behavior of the object. Users of the Sub class object can not invoke behavior of the parent class method if its overridden in sub class.
Lastly yes if you wish to invoke any additional method of Dove
(Sub class ) using a reference of Bird
(Super class) then you need to cast it to Dove
.