Skip to main content

Constructor-1

Constructor:-Constructor is a special type of method which does not have any return type not even void, Constructor is used for instantiation of class. Constructor having some special properties that are given below.

1)      The name of constructor must be same as class name
2)      Constructor must write inside class
3)      Constructor may be multiple type
4)      Constructor can be overloaded
5)      Constructor cannot inherit
6)      All four access modifiers can use for constructor
7)      Constructor cannot call
8)      Constructor automatically invoke at the time of object creation

Example1:- Single constructor with default modifier.

class Student
{
Student()
{
System.out.println("This is constructor");
}
public static void main(String[]args)
{
Student s1=new Student(); 
}
}

Output:-
 C:\JAVATECH>javac Student.java
C:\JAVATECH>java Student

This is constructor

Example2:- Single constructor with default modifier but more object created.

class Student
{
Student()
{
System.out.println("This is constructor");
}
public static void main(String[]args)
{
Student s1=new Student(); 
Student s2=new Student(); 
Student s3=new Student(); 
}
}

Output:-
C:\JAVATECH>javac Student.java
C:\JAVATECH>java Student

This is constructor
This is constructor
This is constructor


Example3:- Single constructor with default modifier but more object created.

class Student
{
static int i=0;
Student()
{
i++;
System.out.println(i+" Object created");
}
public static void main(String[]args)
{
Student s1=new Student();
Student s2=new Student();
Student s3=new Student();
}
}

Output:-
C:\JAVATECH>javac Student.java
C:\JAVATECH>java Student

1 Object created
2 Object created
3 Object created


Example4:-Multiple Constructor-1.

class Student
{

Student()
{
System.out.println("Zero argument Constructor");
}
Student(int a)
{
System.out.println("Parameterized Constructor");
}
public static void main(String[]args)
{
Student s1=new Student();
Student s2=new Student(10);
}
}

Output:-

C:\JAVATECH>javac Student.java
C:\JAVATECH>java Student

Zero argument Constructor
Parameterized Constructor

Example5:-Multiple Constructor-2.

class Student
{

Student()
{
System.out.println("Zero argument Constructor");
}
Student(int a)
{
System.out.println("Parameterised Constructor");
}
Student(Student t)
{
System.out.println("Parameterised Copy Constructor");
}
public static void main(String[]args)
{
Student s1=new Student();
Student s2=new Student(10);
Student s3=new Student(s2);
}
}

Output:-

C:\JAVATECH>javac Student.java
C:\JAVATECH>java Student

Zero argument Constructor
Parameterised Constructor

Parameterised Copy Constructor


Comments