Tutorials

Object Oriented Programming


Java Constructor


To create a new object in java, a constructor needs to be invoked.

Whenever ‘new’ keyword is used then the code contained in the constructors is executed.

A constructor looks almost similar to a method. The constructors does not have a return type like methods. See the example below, Java() does not contain any return type (like void, int, String) 

 

Example

class Java{

    Java() { }  //constructor for Java class

}

Rules for Constructor

  • A constructor should have exactly same name as the class name.
  • Constructor should not have any return type.
  • Constructors can have any access modifier (public, private, protected, default)
  • If programmer doesn’t write any constructor into the class, then a default constructor is automatically provided by the compiler
  • Default constructor is always a no-arg constructor.
  • Abstract classes have constructors and they are always called when a concrete class gets instantiated.
  • Interfaces do not have constructors as they are not the part of object’s inheritance tree.

Constructors are never inherited hence cannot be overridden.

Types of Constructor

There are two types of constructors in java.

  1. Default constructor
  2. Parameterized constructor

Default constructor 

If you donot create your own constructor in java then by default a constructor is created for you. Default constructor doesnot have any parameters. For same reason, default constructor is also called no-arg constructor.

 

When default constructor is provided?

 

Case 1: We do not write any constructor for the class. In this case default constructor will be provided automatically by compiler.

class Java{  

}

When default constructor is not provided?

In all of the below cases, default constructor will not be provided by compiler.

 

Case 1: In the below case, default constructor is not provided.

 

class Java{ 

    Java( ){ }
    Java(String courseCode){ }

}

 

Case 2In the below case, default constructor is not provided.

 

class Java{ 

    Java(String courseCode){ } 

}

Parameterized constructor 

You can also create a parameterized constructors as well. 

The constructors which allows us to pass parameters is known as parameterized consructors.

Parameterized constructors helps in passing value to different object.



Please Share this page
Views : 56