This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus Green #Exam 3 Q57

 
Soum Sark
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following code
class Base {}
class Agg extends Base{
public String getFields(){
String name = "Agg";
return name;
}
}

public class Avf{
public static void main(String argv[]){
Base a = new Agg();
//Here
}
}
What code placed after the comment //Here will result in calling the getFields method
resulting in the output of the string "Agg"?
1) System.out.println(a.getFields());
2) System.out.println(a.name);
3) System.out.println((Base) a.getFields());
4) System.out.println( ((Agg) a).getFields());
The answer is 4.
But since Agg extends Base it has access to the public method then why does 1 fail to compile. Changing the object type to Agg does give the desired answer but why does it fail for Base type. If the method is called runtime on Agg object then it would look for the instance in that object and if not found woundn't it go to the superclass for the method ? What am i missing here ??
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Soum:
This is a classic example of Polymorphism. object reference
a is of type Base but holds an Agg type object.
Polymorphism says that if you call any method on
object a, it will launch at run-time same over-
ridden method in Agg. But the catch is that
this method should also exist in Base class
as well even if it is without body. So if you
add :
public String getfields() { }
in Base class, you will get the result you
are expecting.
Thanks
Barkat
[ August 17, 2002: Message edited by: Barkat Mardhani ]
[ August 17, 2002: Message edited by: Barkat Mardhani ]
[ August 17, 2002: Message edited by: Barkat Mardhani ]
[ August 17, 2002: Message edited by: Barkat Mardhani ]
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Soum, the compiler will complain if the type of the reference on which the method is invoked didn't declare(1) the method.
((Base) a).getFields(); the type is Base
((Agg) a).getFields(); the type is Agg
____________
(1) declared or inherited. That is, the compiler would have accepted if Base hadn't declared getFields() but one of its superclasses had.
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jose. I did not know that inherited method
would work also...
Barkat
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic