Breaking News
Home / Java / Java Tutorials / Understanding Constructors in Java

Understanding Constructors in Java

Constructors in JavaWhat are Constructors?

A Constructor is a special method that is executed by the JVM only once, at the time of creation of an instance of a class. The constructor has to be defined as method that has the same name as that of the class. Also a constructor cannot return any value neither can be declared with a void.

A constructor can used to initialize the member variables to values, or setup the object based on input to constructor, or initialize resources etc.


Can a class have more than one constructor?

Yes, a class can have more than one constructor. Each of the additional constructor method would have same name but different method signatures(method overloading).

What happens if a constructor is not coded for a class?

Having a constructor defined for a class is not an explicit requirement. So if you don’t code for a constructor, the Java Compiler would create a default constructor as class is compiled into byte-code. This constructor would be a no argument constructor.

What is difference between constructor and a regular method?

Both constructor and a regular methods are methods that can be overloaded, however the following are the differences:

  • The constructor method must have the same name as that of the class, the regular method can have any name
  • The construtor method cannot return a value neither is declared with a void, the regular method must return a value or be declared as a void.
  • The constructor method can only be called once, the regular method can be called repeatedly.

How do you call one constructor from another constructors?

Yes, the one constructor can call another constructor of the same class this keyword.

How do you call constructor of a super class?

Yes, the constructor of the super class can be called using the super keyword.

Can you use access modifiers with a constructor?

Yes, access modifiers like public, private & protected etc. can be used to define the accessibility of the constructor from other classes in the same or different packages.

Consider the following snippet for better understanding of Constructors.


The following output is generated:
in : Shape()
in : Rectangle()
Area :50
in : Shape()
in : Shape(len,width)
in : Rectangle(length,width)
Area :10
in : Shape()
in : Shape(len,width)
in : Rectangle(length,width)
in : Rectangle(length,width)
Area :25[pb_builder]

Check Also

Have a Question

How to select a JVM Analyzing Tool?

A JVM monitoring tool also know as a Diagnostic might be needed to fine tune …

Advertisment ad adsense adlogger