Default Constructor in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Default Constructor in Java

Share This

Now, you are familiar with constructors in Java programming language. You know that an object is created by calling the constructor. However, when we have defined the classes, in many cases we have not defined the constructor. But, we have created the objects successfully.

We can create the objects of those classes in which constructors are not defined because JVM provides a default constructor if constructors are not defined. The default constructors do not receive any parameters.

You should know that the default constructor is provided if the class does not have any constructor. If a class contains any constructor, the default constructor can not be called. Still, if you want to call the default constructor, a constructor needs to be defined with a blank definition.

Let us try with examples.
ComplexNum.java
public class ComplexNum { float x; float y; // constructor public ComplexNum(int x, int y) { this.x = x; this.y = y; } }
The following code will not compile, because the default constructor is not available any more.
TestMain.java
public class TestMain { public static void main(String[] args) { ComplexNum cn = new ComplexNum(); } }
But, if the ComplexNum class is defined as follows, the code will compile and run.

ComplexNum.java
public class ComplexNum { float x; float y; }

TestMain.java
public class TestMain { public static void main(String[] args) { ComplexNum cn = new ComplexNum(); } }


Happy Exploring!

No comments:

Post a Comment