What is Constructor Overloading and how can i achieve that in java using an example?
Asked
Active
Viewed 4,308 times
-4
-
2It is already answered [Constructor overloading in Java - best practice](http://stackoverflow.com/questions/1182153/constructor-overloading-in-java-best-practice) – Subhrajyoti Majumder Feb 21 '13 at 08:47
-
http://www.leepoint.net/JavaBasics/oop/oop-45-constructor-overloading.html – Iswanto San Feb 21 '13 at 08:47
2 Answers
1
Consider the code below, the constructor is overloaded and can be called either with...
new Tester();
or
new Tester("Hello world!");
These would both be valid in the given class
class Tester {
public Tester() {
}
public Tester(String overloaded) {
System.out.println(overloaded);
}
}

David
- 19,577
- 28
- 108
- 128
1
This is an example
class MyClass{
public MyClass(){
System.out.println("Constructor without parameters");
}
public MyClass(int a){
//overloaded constructor
System.out.println("Constructor with 'a' parameter");
}
}
You can create multiple "versions" of the class constructor. This is the meaning of method overload. You can overload almost any method of a Java class.
Take a look to official Java tutorial at http://docs.oracle.com/javase/tutorial/
More information on http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html and http://www.java-samples.com/showtutorial.php?tutorialid=284

Lobo
- 4,001
- 8
- 37
- 67