Tutoriallearn.com

Easy Learning


Home

Search Tutoriallearn.com :



Java Overloaded Constructor

  • Many constructors can be defined in the class. All constructors have same name as class name.
  • This is called constructors are overloaded (i.e. Overloaded constructor).
  • Overloaded constructors provide flexibility to create objects in various ways.

Example

class student {
     
		int rollno;
		String name;

      student(int r, String n) // constructor is defined, it has same name as class name 
      {
         rollno = r;
         name = n;
       }
	 student(int r) // one more constructor is defined, it has same name as class name 
      {
         rollno = r;
         name = "Gargi";
       }
      display ()
       {
        System.out.println ("roll no is " + rollno);
		System.out.println ("name is "+ name);
	  } 
}

class demostudent {

   public static void main (String args[])
	{

      student s1 = new student(10, "Rajesh");  // two arguments constructor will be called
      student s2 = new student(12)  // one argument constructor will be called

      s1.diaplay();
	  s2.display();
    }

}

Explanation of the program

  • The program defines a class named 'student'.
  • Within the class 'student', two constructors are defined, it is called overloading of constructor.
  • In main() method of class 'demostudent', two objects (s1 and s2) are created.
  • The statement 'student s1 = new student(10, "Rajesh")' creates an object named s1. It calls two arguments constructor.
  • The statement 'student s1 = new student(12)' creates an object named s2. It calls one argument constructor.
  • The method display() is called using the object s1 and s2 to display values of variables of both objects.

Output of the program

roll no is 10
name is Rakesh
roll no is 12
name is Gargi


© Copyright 2016-2026 by tutoriallearn.com. All Rights Reserved.