A default constructor helps create an object without needing to give any details first.
0
0
Default constructor in Java
Introduction
When you want to create an object quickly without setting values right away.
When you want Java to automatically provide a simple way to make objects.
When you plan to set object details later using other methods.
When you write a class and don't add any constructor yourself.
When you want to avoid errors from missing constructors.
Syntax
Java
public ClassName() { // optional code }
If you do not write any constructor, Java adds this default one automatically.
You can write your own default constructor to add setup code.
Examples
This class has a default constructor that does nothing extra.
Java
public class Car { public Car() { // This is a default constructor } }
This default constructor sets the title to "Unknown" when a Book is created.
Java
public class Book { private String title; public Book() { title = "Unknown"; } }
Sample Program
This program creates a Person object using the default constructor. It sets the name to "No name" and then prints it.
Java
public class Person { String name; // Default constructor public Person() { name = "No name"; } public void showName() { System.out.println("Name: " + name); } public static void main(String[] args) { Person p = new Person(); p.showName(); } }
OutputSuccess
Important Notes
If you add any constructor with parameters, Java will NOT add a default constructor automatically.
Always add a default constructor if you want to create objects without arguments after adding other constructors.
Summary
A default constructor lets you create objects without giving details.
Java adds it automatically if you write no constructors.
You can write your own to set default values or run code when objects are made.