Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor overloading problem

 
Kasem Boonmun
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Kasem Boonmun
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic