Java Constructors
A constructor is a special method that initialises an object. It has the same name as the class and no return type, and it runs automatically when the object is created.
Types
- Default (no-arg) constructor
- Parameterized constructor
class Emp {
String name; int id;
Emp() { // default
name = "Unknown"; id = 0;
}
Emp(String name, int id) { // parameterized
this.name = name;
this.id = id;
}
void show() { System.out.println(name + " " + id); }
}
new Emp().show();
new Emp("Neha", 101).show();
Unknown 0
Neha 101
NoteIf you write no constructor, the compiler supplies a default one. Once you write any constructor, it doesn't.
Track your progress through the Java course