Lesson 16 of 36Article16 min
Constructors & this
Constructor runs when you use new. Same name as class, no return type. Use it to set initial field values.
Constructors — setup new objects
Constructor runs when you use new. Same name as class, no return type. Use it to set initial field values.
If you write no constructor, Java adds a default no-arg constructor.
Real-life example: Constructor is the factory setup line — when a new phone rolls out, it gets default settings before shipping.
Constructor example
class User {
String name;
int age;
User(String name, int age) {
this.name = name;
this.age = age;
}
}
User u = new User("Asha", 20);this — refer to current object
this refers to the current object. Common use: this.field = param when names clash.
this() calls another constructor in the same class — must be first line.
Real-life example: Saying "this phone" in a shop means the one in your hand, not every phone on the shelf.
this keyword
class Rectangle {
int width, height;
Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
int area() {
return this.width * this.height;
}
}