Core Java Tutorial

Core Java Tutorial

Constructor Overloading in Java

Constructor overloading in Java

The Java programming language supports overloading constructor, You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.

Example
public class Student {

 String name;

 int age;

 String email;

 public Studtent(String name, int age)

 {

  this.name = name;

  this.age = age;

 }

 public Studtent(String name, int age, String email)

 {

  this.name = name;

  this.age = age;

  this.email = email;

 }

 public void display()

 {

  System.out.println(name);

  System.out.println(age);

  System.out.println(email);

 }

 public static void main(String[] args) {

  Student s1 = new Student("Shanthi", 20);

  Student s2 = new Student("Veera", 25, "veera@candidjava.com");

  s1.display();

  s2.display();

 }

}

Rules for overloading

  • Constructor overloading can appear only in the same class.

  • Overloaded constructor MUST change its number of argument or its type.

  • Overloaded constructor CAN change the access modifier.

  • Overloaded methods CAN declare new or broader checked exceptions.

Legal overloading

Overloaded constructor should have different argument.

public class Student {

 public Student(int i, int j)

 {

 }

 public Student(int i)

 {

 }

}

It’s legal for Overloaded constructor to change only its type.

public class Student {

 public Student(int i)

 {

 }

 public Student(float i)

 {

 }

}

Overloaded constructor can have different access modifiers.

public class Student {

 public Student(long i)

 {

 }

 private Student(char c)

 {

 }

}

Overloaded constructor can declare new or checked exception.

public class Student {

 public Student(int i)

 {

 }

 public Student(short s) throws Exception

 {

 }

}