• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor overloading

 
prabakaran perumal
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
--------------------------------------------------------------------------------
class ThreeConst {
public static void main(String[] args) {
new ThreeConst();
}

public void ThreeConst(int x) {
System.out.print(" " + (x * 2));
}

public void ThreeConst(long x) {
System.out.print(" " + x);
}

public void ThreeConst() {
System.out.print("no-arg ");
}
}

The above code prints no output but my doubt is as per overloading rule different arg. type only allowed then how is it possible?
 
Jerry Ragland
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All the three are methods they are not constructors because they have a return type. In this class a default constructor will be added by the compiler.

-Jerry
 
vinoth m
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Prabakar,

My understanding is this not overloading the constructor but it is new method with the same name as constructor. As you have mensioned the return type it will not be taken as constructor signature it will be considered as a method signature only....

Regards,
Vinoth M
 
prabakaran perumal
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vinoth

It means that we can create method with same constructor name. Am i right?
 
yogesh gargate
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Prabhakar,

Constructor's name is nothing but the Class's name. And constructor do not contain any return type. (if it is containing then it's method).
You can have method with the class/costructor name. No problem.
But the method is not invoked when you create instance of class, if you want to invoke that method you have to invoke it explicitely.

...yogesh
 
prabakaran perumal
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks... I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic