Constructor in JAVA

 

Constructor in Java

CONSTRUCTOR IN JAVA:-

The constructor in Java is very similar to the method. The main job of the constructor is to initialize the object. The constructor is a block of code that initializes the newly created object. A constructor is called automatically when a new instance of an object is created.
Each and every class in Java contain a constructor.
Java support two types of constructor:-default constructor, and copy constructor

Calling Procedure:-

1)new keyword

2)this keyword

3) Super keyword

Default constructor:-

The constructor without any argument is known as default constructor. The access specifier of the default constructor is same as the class access specifier. If there is no constructor defined by the user explicitly java compiler will provide the default constructor.

Parameterize Constructor:- 

The constructor which is designed by the user known as the parameterized constructor. If the user already defined a constructor then the compiler doesn’t provide any default constructor

PROGRAM:-

Class Test

{

Test(int x)

{

System.out.println(“I am in parameterise constructor”);
}

public static void main(String[] args)

{

new Test(123);

}

}

O/P=I am in parameterized constructor

 

  1. Copy constructor

  • If the constructor is responsible to copy the contents of one object to another then this is known as copy constructor.
  1. Private Constructor

  • The constructor declared with a private keyword is known as the private constructor.
  • If the constructor is private we cannot create an object outside class.

 

PROGRAM:-

class Student

{

int roll;

String name;




Student (Student k)

{

roll=k.roll;

name=k.name;

}

Student()

{




}

public static void main(String[] args)

{

Student s1=new Student();

System.out.println("state of s1:"+s1.roll+"\t\t"+s1.name);

s1.roll=100;

s1.name="abc";

System.out.println("state of s1:"+s1.roll+"\t\t"+s1.name);

Student s2=new Student(s1);

System.out.println("state of s2:"+s2.roll+"\t\t"+s2.name);

s2.roll=101;

s2.name="abcd";

System.out.println("state of s2:"+s2.roll+"\t\t"+s2.name);

Student s3=new Student(s2);

System.out.println("state of s3:"+s3.roll+"\t\t"+s3.name);

s3.name="abcde";

s3.roll=102;

System.out.println("state of s3:"+s3.roll+"\t\t"+s3.name);

Student s4=new Student(s3);

System.out.println("state of s4:"+s4.roll+"\t\t"+s4.name);

}

}




O/P

state of s1:0           null

state of s1:100         abc

state of s2:100         abc

state of s2:101         abcd

state of s3:101         abcd

state of s3:102         abcde

state of s4:102         abcde

Leave a comment

Your email address will not be published. Required fields are marked *