.


Divya

Java constructor


Constructor:

  1. The constructor is used to initialise the object not to create the object .
  2. New A() is used to create an object inside heapmemory in java that object called instance.

syntax

A a = new A();

Rules of writing constructor:

  1. Name of class and name of the constructor should be same.
  2. Return type concept not applicable for constructor even void also.
  3. only modifier applicable for consructor are public,private,protected.

Example

public class Student {
string name;
int roll no;
student(string name,int rollno)
{
this name=name;
this rollno=rollno;
}
public.static.void main(string[ ]args)
{
student s1 =new student("mitra",101);
student s2=new student ("ravi",102);
}
}

Example

public class farmer {
public String farName; // farmer name
public double hourly_rate, hours_worked;
Employee(String name, double pay, double hours) {
farName = name;
pay_rate = pay;
hours_worked = hours;
}
public static void main(String[] args) {
Farmer new Farmer= new Farmer("");
}
}

Difference between constructor and instance block:

constructor:

To perform initialisation of object.

Instance block:

Other than initialisation if we want to perform any activity for every object creation than we go for instance block.



.