Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock Exam question.

 
rakshak rai
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Dave Walsh
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it .. Thanks guys
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic