-4

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

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Lobo...It has helped a lot..
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);
    }
}

1 Comment

Thank you David for the example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.