DEV Community

Indumathy
Indumathy

Posted on

Contstructor

Constructor is a special method used to initialize an value for instance variable when the object created.

  • When we created and object, constructor will automatically run.

  • Constructor name will be the class name

Syntax:
Class Name
{
int id;
Name(int id) //constructor
}

Why Constructor?

  • It is used to Initialize the value immediately.

  • No chance for creating incomplete object.

Types of Constructor:

  1. Default constructor
  • No parameter
  • Provided by java if we don't provide any constructor.
  1. Parameterized constructor:
  • Has parameter.
  • Used to pass value while creating object.

Example:
Test(int a)
{
System.out.println(100);
}

Example for constructor:

Scenario: In the student register name and roll no must be entered initially.

package moduleFour;

public class College {
int rollno;
String name;

College(int rollno,String name)
{
    this.rollno = rollno;
    this.name = name;
}
public static void main(String[] args) {
    College student1 = new College(2001,"Kavin");
    College student2 = new College(2002,"Nethra");
    System.out.println(student1.rollno);
    System.out.println(student2.name);;
}
Enter fullscreen mode Exit fullscreen mode

}

Output:
2002
Nethra

_Constructor Overloading: _

Constructor overloading is creating object in different ways with multiple constructor with different parameter.

(i.e) having more than one constructor in same class with different parameter

Why?

  • To create object in different ways.

  • To provide default or custom values for object.

Example for Constructor Overloading:

package moduleFour;

public class College2 {
int rollno;
String name;
int age;

College2(int rollno,String name,int age)
{
this.rollno = rollno;
this.name = name;
this.age = age;
}
College2(int rollno,String name)
{
this.rollno = rollno;
this.name = name;
}
public static void main(String[] args) {
College2 student1 = new College2(2001,"Kavin",18);
College2 student2 = new College2(2002,"Nethra");
System.out.println(student1.rollno); //2001
System.out.println(student1.age); //18
System.out.println(student2.name); // Nethra
}
}

Top comments (1)

Collapse
 
vpospichal profile image
Vlastimil Pospíchal

Please indicate the language the post is in.