DEV Community

pranavinu
pranavinu

Posted on

Constructor

this:
1)It is a keyword
2)When the variable names are same,It is used to
differentate inbetween the instant and local variable

Ex: this.student=student;

constructor:
1)The constructor name only should be a class name
2)The Constructor is called,when the object is created
3)It is to intilize the value for an instance variable at the object creation
4)The values inside the parameter of an object creation is passed to the corresponding local variables and then values is asigned to the instance variables

Syntax:
class name()
{

}

Senario-2
When a student is registered, roll number and name are mandatory.
So they must be passed during object creation.

{

String name;
int roll;



school(String name,int roll)
{

    this.name=name;
    this.roll=roll;
}

public static void main(String[] args)
{


    school student1 =new school("ravi",23);
    System.out.println(student1.roll);
    System.out.println(student1.name);
}
Enter fullscreen mode Exit fullscreen mode

}

constructor overloading:
1)It has a multiple constructor with different parameters

Top comments (0)