wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Mock Exam question. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mock Exam question." Watch "Mock Exam question." New topic
Author

Mock Exam question.

rakshak rai
Greenhorn

Joined: Aug 16, 2007
Posts: 3
class Base
{
int i = 90;
public void amethod()
{
System.out.println("Base.amethod()");
}
Base()
{
amethod();
}
}

public class Derived extends Base
{
int i = -1;
public static void main(String argv[])
{
Derived d = new Derived();
System.out.println("");
Base b = new Derived();
System.out.println(b.i);

}
public void amethod()
{
System.out.println("Derived.amethod()");
}
}


Output for the above code comes out as

Derived.amethod()

Derived.amethod()
90

Can somebody explain why does Derived.amethod() comes for Derived d = new Derived();
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Howdy Rakshak,


this seems to be your first posting, so:

Welcome to the ranch!



your question was:
Can somebody explain why does Derived.amethod() comes for Derived d = new Derived();


Class Derived looks as if it does not have its own constructor. But it has. If you don't provide one, the compiler invisibly adds on that should look like:


The super calls the no-args constructor of class Base and there the method is called.
Note that the call of method also works polymorphically and calls the overridden method of the sub class.



By the way, you may have noticed that the code you pasted in has lost all of its indentations.
To indent your code properly:

At the posting page, mark the part of your posting that should be indented. Usually that will be your code (or some tabellaric output).

Hit the - Button below.
that's it!


Yours,
Bu.


all events occur in real time
Dave Walsh
Greenhorn

Joined: Jun 21, 2007
Posts: 24
It's because Derived's unimplemented default constructor calls Base's contrusctor, which calls amethod() but at runtime, polymorphism comes into play and and the call is transfered to Derived's amethod().
rakshak rai
Greenhorn

Joined: Aug 16, 2007
Posts: 3
Got it .. Thanks guys
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Mock Exam question.
 
Similar Threads
Method from constructor
Please explain this question from mock exam.
How is this??
inheritance question
Doubt in Mock Question