All about Constructor [Types][Execution][Examples]
A special type of method, which is used to construct memory for class elements, is called as constructor.

Example :
class A
{
 A()
  {
  }
}


It's specialties are

  • It's name and class name is same.
  • It executes implicitly on object creation statements.
  • Constructors cannot be executed explicitly by objects that one constructor in it's life time.
  • Constructor doesn't have any return type not even void


Example :
class AB
{
 AB()
 {
  System.out.println("Hello Constructor");
 }
 public static void main(String args[])
 {
  AB a1=new AB();
  AB a2=new AB();
  AB a3=new AB();
  AB a4=new AB();
  }
}


Types of Constructor :

There are two types of constructor in Java.

1.Default Constructor :

A constructor which does not accept arguments, is called the default constructor.

Parameterized Constructor :

A constructor which have parameters and accepts arguments at runtime is called as parameterised constructor.


Write a program to define constructors overloading.
class ABC
{
 ABC()
 {
  System.out.println("Default constructor");
 }
 ABC(int x)
 {
  System.out.println("X is "+x);
 }
 ABC(float p)
 {
  System.out.println("P is "+p);
 }
 ABC(int a,int b)
 {
  System.out.println("A is "+a+" B is "+b);
 }

public static void main(String args[])
 {
 ABC a1= new ABC();
 ABC a2= new ABC(100);
 ABC a3= new ABC(12.5);
 ABC a4= new ABC(1,10);
 }
}


Construction execution criteria[Process] :

There are four steps in execution criteria of Constructor.
  1. TO create context.
  2. To load the class data into that context.
  3. To initialize all the uninitialized data of context.
  4. To execute it's own body.

Axact

Narendra

Hello, everyone! I am Narendra Bagul founder of Javanotes9. First of all thank you for visiting my blog. Hope you all like my java notes as well. I'm young part time blogger and a Computer Engineering student. I started blogging as a hobby. Now here I'm sharing my little acquired knowledge about my favorite programming language JAVA.

Post A Comment: