Nearby lessons
33 of 125Java - Constructors
📌 What You Will Learn
- What class and object mean, with real-life examples
- The four pillars: Encapsulation, Abstraction, Inheritance, Polymorphism
- Constructors, this, super, static and final
- Method overloading and method overriding (with a comparison table)
- Abstract classes and interfaces (including the modern changes)
- Association, Aggregation and Composition
Constructors is a core concept of the Java language. This lesson explains Constructors and The this Keyword with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Constructors
A constructor is a special method that runs automatically when an object is created. Its job is to initialise the object. Rules:
- The constructor name is exactly the same as the class name.
- It has no return type, not even void.
- It is called automatically by new. You never call it manually.
Trainer's Note: If you write no constructor, Java adds a default no-arg constructor automatically. But if you write any constructor yourself, Java does not add the default one. So a class with only a parameterised constructor cannot be created with new ClassName().
Example01
The this Keyword
Inside an instance method or constructor, `this` refers to the current object. It is mainly used to remove the confusion between instance variables and local parameters with the same name.
this() (with brackets) can also call another constructor of the same class — this is called constructor chaining.
Example02
📝 Key Takeaways
- Class = blueprint; Object = real thing made from it (memory in heap).
- Four pillars: Encapsulation (hide data), Abstraction (show only essentials), Inheritance (reuse parent code), Polymorphism (one name, many forms).
- Overloading = same class, different parameters, decided at compile time. Overriding = child redefines parent method, decided at run time.
- Constructor initialises the object; name = class name, no return type.
- this = current object; super = parent class; static = belongs to class; final = cannot change.
- abstract class cannot be instantiated; interface is a contract a class implements.
- Association (weak), Aggregation (has-a, part independent), Composition (strong has-a, part dies with whole).
🧠 Test Your Knowledge
1 QuestionsProgress: 0 / 1