group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
262 Members
Join this group to post and comment.
AdhikariHarika Reshma
AdhikariHarika Reshma
Computer Science
29 Jan 2019

What is a Constructor in java?What are the rules for defining a Constructor and its types?

Constructor is just like a method in java that is used to initialize the state of an object and will be invoked during the time of object creation.

Rules for defining a Constructor:

1.Constructor name should be same as class name.

2.It cannot contain any return type.

3.It can have all the access modifiers (public,private, default, protected) but cannot have non access modifiers (final,static, abstract, synchronized).

4.No return statement is allowed.

5.It can take any number of parameters.

6.Constructor can throw an exception,we have throws clause.

We can have a class with no constructor,when the compiler encounter a class with no constructor then it will automatically create a default constructor.A constructor cannot return any explicit value but implicitly it will be returning the instance of the class.

Types of constructor:

1.Default Constructor:If we don't implement any Constructor in our class java complied inserts a default constructor into code on behalf of programmer.This is known as default constructor.

2.No-arg Constructor: Constructor with no arguments is known as no-arg constructor.The body of the program can have any code unlike default constructor where the body of the constructor is empty.

3.Parametrized Constructor: Constructor with arguments is known as parametrized constructor.



Shruthi Pillai
Shruthi Pillai
Information Technology
2mos ago

A constructor is collection of statements(i.e. instructions) that are executed at time of Object creation.  Constructor is invoked at the time of object or instance creation. 

Rules for writing constructor

1) Constructor of a class must has same name as the class name.

2)A constructor in Java can not be abstract, final, static and Synchronized.

3)Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.