• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Confusion in overloaded constructors

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the following code :


public class Three
{
float f;
Three()
{
this(5);
System.out.println("In No arg type" + f);
System.out.println("In No arg type" + this.f);
}


Three(float f)
{

System.out.println("In Arguments type" + f); // output is 5.0
System.out.println("In Arguments type" + this.f); //output is 0.0
}

public static void main(String args[])
{
Three t = new Three();
}
}


Can anyone please explain why the output for first println statement is coming 5.0 and the secong one ( call to this.f ) results to 0.0 why does the value for two statement is not 5.0 ?
why does the value for (this.f) is not set to 5.0 ?
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
f in Three(float f) is the local copy of f but when you refer to this.f it refers to the class variable f whose value is 0 as it is not initialized. the f in Three(float f) hides the class variable f.
 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Kumar

to set the this.f to 5.0 you have to use this.f = f; in constructor Three(float f).



By doing this you will get all the output values for f as 5.0.
For constructor Three(float f) , the f is local variable, whose scope is limited to the constructor[Three (float f)] only.


Regards
Shashikant
 
kumar shinde
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank-you very much Roohan & Shashikant.... now I understand it perfectly ...
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic