Constructor in Java


In Java, constructor is a block of codes similar to method. It is called when an instance of object is created and memory is allocated for the object.
It is a special type of method which is used to initialize the object.

Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Rules for creating java constructor

There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors in java:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

loading...

No comments:

Powered by Blogger.