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

Constructor overloading problem

Kasem Boonmun
Greenhorn

Joined: Dec 14, 2003
Posts: 4
Hi All,
I'm get confused with constructor overloading. As my understanding, compiler does not allow us to have two methods with identical signature but different return types, access modifier and exception. And, constructor always has the name of the class and no return type.
Would you please help me out this problem?
1. Why I still can overload constructor with return type?
2. Why call "x.overload(1)" which expect integer return without any problem?
TIA,
Kasem
----------------------------------------------------------------------]
class overload
{
//Number 1
overload()
{
System.out.println("default constructor");
}
//Number 2
overload(int x)
{
System.out.println("int constructor");
}
//Number 3
public int overload(int x)
{
System.out.println("public int overload");
return 1;
}
//Number 4
private long overload(long x)
{
System.out.println("private long overload");
return 1l;
}
}
public class overloadTest
{
public static void main(String[] args)
{
overload x = new overload(1);
long y = x.overload(1);
//running OK even though this method RETURN integer. Why?
x.overload(1);
}
}
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451

1. Why I still can overload constructor with return type?

Because the methods:

are not constructors but instance methods of the overload class. There is no restriction in the java spec for giving a method the same name as the class. A consturctor implicitly returns a reference to the correct type of object.

2. Why call "x.overload(1)" which expect integer return without any problem?

Because as I stated above, you have a public method with the correct signature which just happens to have the same name as the class.


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Kasem Boonmun
Greenhorn

Joined: Dec 14, 2003
Posts: 4
Thank you
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constructor overloading problem
 
Similar Threads
boxing
var-args and overloading
Boxing & Widening
K&B Mock Question 5
method overloading issues