Consider the following code fragment, taken from some package:
public class Maryland extends State
{
Maryland( )
{ /* null constructor */
}
public void printMe( )
{
System.out.println("Read it.");
}
public static void main(String[ ] args)
{
Region east = new State( );
State md = new Maryland( );
Object obj = new Place( );
Place usa = new Region( );
md.printMe( );
east.printMe( );
((Place) obj).printMe( );
obj = md;
((Maryland) obj).printMe( );
obj = usa;
((Place) obj).printMe( );
usa = md;
((Place) usa).printMe( );
}
}
class State extends Region
{
State( )
{
/* null constructor */
}
public void printMe( )
{
System.out.println("Ship it.");
}
}
class Region extends Place
{
Region( )
{
/* null constructor */
}
public void printMe( )
{
System.out.println("Box it.");
}
}
class Place extends Object
{
Place( )
{
/* null constructor */
} public void printMe( )
{
System.out.println("Buy it.");
}
}
What is the output from calling the main( ) method of the Maryland class?
Output:
Read it.
Ship it.
Buy it.
Read it.
Box it.
Read it.
Explanation:
md.printMe() and east.printMe() are straight forward calls.
md takes the reference of State type and pointing to the object of Maryland
east take the reference of Region class and pointing to the object of State.
so md and east objects calls the methods from which objects they are pointing to. which gives output
Read it.
Ship it.
((Place) obj).printMe( );
Object is parent class for all the classes defined in java language.
obj is pointing to Place object. obj is typecasting to Place before calling method.
obj calls the method from Place class.i.e., "Buy it."
obj = md;
((Maryland) obj).printMe( );
storing the object of md in obj. as md have the object of Maryland and calls the method from that class which is "Read it."
obj = usa;
((Place) obj).printMe( );
storing the object of usa in obj. as usa have the object of Region class, above line calls the method from Region class.i.e.,, "Box it."
usa = md;
((Place) usa).printMe( );
stores the object of md in usa. as md referensing the maryland object, it call the method from that class and print's "Read it."