Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructors

 
Kondapally Ashwin
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Base{
int value = 0;
Base(){
addValue();
}
void addValue(){
value += 10;
}
int getValue(){
return value;
}
}
class Derived extends Base{
Derived(){
addValue();
}
void addValue(){
value += 20;
}
}
public class Test {
public static void main(String[] args){
Base b = new Derived();
System.out.println(b.getValue());
}
}

The output is 40. Can anyone help me in understanding how 40 is the output?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The derived addValue() method is called twice. Once from the base constructor, and once from the Derived constructor. Since the runtime type of b is a Derived, the addValue method that is called from is is always the overridden one in the Derived class. I added some println() statements in your code to illustrate.
 
Shafian Kisna
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

Can someone care to explain to me what does this statement imply..
Base b = new Derived();
I am trying to derive the flow and am uncertain as to why it moves abt all over the place...
I am brushing up on the basics of the language...so do be patient if my qn is blunt....

thanks..
 
Stephen Foy
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shafian Kisna:
hi,

Can someone care to explain to me what does this statement imply..
Base b = new Derived();
I am trying to derive the flow and am uncertain as to why it moves abt all over the place...
I am brushing up on the basics of the language...so do be patient if my qn is blunt....

thanks..


Creates an instance of the class Base and instantiates it with the null constructor from Derived.
 
Henry Wong
author
Marshal
Pie
Posts: 20998
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shafian Kisna:
hi,

Can someone care to explain to me what does this statement imply..
Base b = new Derived();


This instruction declares a reference variable "b", which is assigned to a Derived object instantiated using the constructor that takes no parameters. This assignment works because the Derived object is-a Base object.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic