Default constructor in java

Previous
Next

Default constructor:

  • Compiler adds a zero args constructor with empty body is called default constructor.
  • We can check compiler added code using “javap” command
public class Test 
{
	public static void main(String[] args) 
	{
		new Test(); // No error : It invokes default constructor
	}
}

Compiler doesn’t add default constructor when we define any constructor explicitly in class definition.

public class Test 
{
	Test(int a)
	{
		// logic...
	}
	public static void main(String[] args) 
	{
		new Test();  // Error : No such constructor
	}
}

We need to define all required constructors explicitly in the application:

public class Demo 
{
	Demo()
	{
		// zero args...
	}
	Demo(int x)
	{
		// args constructor...
	}
	public static void main(String[] args) 
	{
		new Demo();  
	}
}
Previous
Next

Add Comment

Courses Enquiry Form