Вы находитесь на странице: 1из 7

Constructors

Constructors
 In Java, constructor is a block of codes similar to method. It
is called when an instance of object is created and memory is
allocated for the object.
 It is a special type of method which is used to initialize the
object.
 It is called constructor because it constructs the values at the
time of object creation.
 It is not necessary to write a constructor for a class. It is
because java compiler creates a default constructor if your
class doesn't have any.
Constructor
 Rules
 Constructor name must be same as its class name
 Constructor must have no explicit return type
 Types of java constructors
 Default constructor (no-arg constructor)
 Parameterized constructor
Default constructor
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Parameterized constructor
class Student{ void display(){
int id; String name; int age; System.out.println(id+" "+name+" "+age);
Student(int i,String n){ }
id = i;
name = n; public static void main(String args[]){
} Student s1 = new Student(111,"Karan");
Student(int i,String n,int a){ Student s2 = new Student(222,"Aryan",25);
id = i; s1.display();
name = n; s2.display();
age=a; }
} }
Difference between constructor and
method in java
Java Constructor Java Method

Constructor is used to initialize the Method is used to expose behaviour


state of an object. of an object.

Constructor must not have return Method can have return type.
type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default Method is not provided by compiler


constructor if you don't have any in any case.
constructor.

Constructor name must be same as Method name may not be same as


the class name. class name.
Copy Constructor
void display(){
class Student{
System.out.println(id+" "+name);
int id;
}
String name;
Student(int i,String n){
public static void main(String args[]){
id = i;
Student s1 = new Student(111,"Karan");
name = n;
Student s2 = new Student(s1);
}
s1.display();
s2.display();
Student(Student s){
}
id = s.id;
}
name =s.name;
}

Вам также может понравиться