aspose file tools*
The moose likes Beginning Java and the fly likes constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructors" Watch "constructors" New topic
Author

constructors

Kondapally Ashwin
Greenhorn

Joined: May 16, 2006
Posts: 25
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

Joined: Jan 17, 2006
Posts: 1296
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.


Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Shafian Kisna
Ranch Hand

Joined: Oct 25, 2005
Posts: 70
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

Joined: Oct 17, 2005
Posts: 143
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.


Stephen Foy - Microsoft Application Development Consultant
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18977
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: constructors