Constructor in java

CONSTRUCTOR –

Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. [Tutorial Points]

Once we create a class in java each time we need a object to call this, so there are a lot of methods to create aobject

  1. new keyword
  2. Instance factory keyword
  3. static factory keyword
  4. pattern factory method
  5. newInstance() method
  6. clone() method
  7. Deserialization method

Out of which today we will study in detail about new keyword

Rules to declare constructor in Java

  1. Constructor name and class name must be same.
  2. Constructor able to take parameters.
  3. Constructor not allowed return type.

Types of constructor

  1. Default constructor (0-argument-cons. or empty Impl.)
  2. User defined constructor (parameterized cons.)
  1. Default constructor – 

JVM not constructed any type of constructor. During compilation compiler check the new  constructor_name() *. If not available compiler generates the default constructor.

So the default constructor is always created by Compiler and at runtime executed by JVM.

class Test{

void m1() //instance method

{ System.out.println(“m1 method”);  }

/*default constructor created by compiler

Test()

{ //empty implementation }

*/

public static void main(String[] args)

{

Test t= new Test();

t.m1();

}

}

 

2. User defined constructor- 

This Constructor is defined by users. Users can modify according to the needs.  

class Test{

void m1()                    //instance method

{

System.out.println(“m1 method”);

}

Test()                      //user defined constructor

{

System.out.println(“ud const”);

}

Test(int a)                      //user defined constructor with parameter

{

System.out.println(“ud const”);

}

public static void main(String[] args)

{

Test t= new Test();               //constructor will executed just after creating the object

Test t1= new Test(5);

t.m1();           //method calling

}

}

 

 

Advertisements

One thought on “Constructor in java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s