-4

What is Constructor Overloading and how can i achieve that in java using an example?

Karanja
  • 23
  • 1
  • 8

2 Answers2

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