What is Constructor Overloading and how can i achieve that in java using an example?
-
2It is already answered Constructor overloading in Java - best practiceSubhrajyoti Majumder– Subhrajyoti Majumder2013-02-21 08:47:11 +00:00Commented Feb 21, 2013 at 8:47
-
leepoint.net/JavaBasics/oop/oop-45-constructor-overloading.htmlIswanto San– Iswanto San2013-02-21 08:47:16 +00:00Commented Feb 21, 2013 at 8:47
Add a comment
|
2 Answers
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
1 Comment
Karanja
Thank you Lobo...It has helped a lot..
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);
}
}
1 Comment
Karanja
Thank you David for the example