Yes, Java supports constructor overloading. We create multiple constructors with the same name but with different parameters types or with different no of parameters.
public class Person {int id;String name;int age;public Person() {System.out.println("Default constructor..");}public Person(int id, int age) {this.id = id;this.age = age;}public Person(String name) {this.name=name;}public static void main(String[] args) {Person person=new Person("Ram");System.out.println("ID="+person.id+", Age="+person.age+",Name="+person.name);Person person1=new Person(1,24);System.out.println("ID="+person1.id+", Age="+person1.age+",Name="+person1.name);}}// ID=0, Age=0, Name=Ram// ID=1, Age=24, Name=null
The process of defining multiple constructors of the same class is referred to as Constructor overloading. However, each constructor should have a different signature or input parameters. In other words, constructor overloading in Java is a technique that enables a single class to have more than one constructor that varies by the list of arguments passed. Each overloaded constructor is used to perform different task in the class.
The Java compiler identifies the overloaded constructors on the basis of their parameter lists, parameter types and the number of input parameters. Hence, the constructors that are overloaded should have different signatures. A constructor’s signature contains its name and parameter types. An ambiguity issue arises when two of the class constructors have an identical signature.
Use of this () in constructor overloading
However, we can use this keyword inside the constructor, which can be used to invoke the other constructor of the same class.
public class Person {int id;String name;int age;public Person() {System.out.println("Default constructor..");}public Person(int id, int age) {this.id = id;this.age = age;}public Person(String name) {this(1, 25); // using this calling another constructorthis.name=name;}public static void main(String[] args) {Person person=new Person("Ram");System.out.println("ID="+person.id+", Age="+person.age+",Name="+person.name);}}// ID=1, Age=25, Name=Ram
No comments:
Post a Comment