freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Constructors:-

1) Constructors are executed as part of the object creation.
2) If we want to perform any operation at the time of object creation the suitable place is constructor.
3) Inside the java programming the compiler is able to generate the constructor and user is able to declare the constructor. so the constructors are provided by compiler and user.
There are two types of constructors
1) Default Constructor.
     a. Zero argument constructor.
2) User defined Constructor
     a. zero argument constructor
     b. parameterized constructor

Java Images

Default Constructor:-

1) in the java programming if we are not providing any constructor in the class then compiler provides default constructor.
2) The default constructor is provided by the compiler at the time of compilation.
3) The default constructor provided by the compiler it is always zero argument constructors with empty implementation.
4) The compiler generated default constructor that default constructor is executed by the JVM at the time of execution.

Before compilation

class Test
{
void good()
{
System.out.println("good program");
}
public static void main(String[] args)
{
Test t=new Test();
t.good();
}
}

After compilation:-

class Test
{
Test()
{ default constructor provided by compiler
}
void good()
{
System.out.println("good program");
}
public static void main(String[] args)
{
Test t=new Test();
t.good();
}
}

User defined constructors:-

Based on the user requirement user can provide zero argument constructor as well as parameterized constructor.
Rules to declare a constructor:-
1) Constructor name must be same as its class name.
2) Constructor doesn’t have no explicit return type if we are providing return type we are getting any compilation error and we are not getting any runtime errors just that constructor treated as normal method.
3) In the class it is possible to provide any number of constructors.

user provided zero argument constructors.

class Test
{
Test()
{
System.out.println("0-arg cons by user ");
}
public static void main(String[] args)
{
Test t=new Test();
}
}

intput and output

output:O-arg cons by user

user provided parameterized constructor is executed.

class Test
{
Test(int i)
{
System.out.println(i);
}
void print()
{
System.out.println("freetimestudy");
}
public static void main(String[] args)
{
Test t=new Test(10);
t.print();
}
}

intput and output

output:10,,freetimestudy

constructor overloading

class Test

Test()
{
System.out.println("this is zero argument constructor");
}
Test(int i)
{
System.out.println(i);
}
Test(int i,String str)
{
System.out.println(i);
System.out.println(str);
}
public static void main(String[] args)
{
Test t1=new Test();
Test t2=new Test(10);
Test t3=new Test(100,"hi");
}
}

intput and output

output:this is zero argument constructor,,10,,100,,hi