Module 7: Object-Oriented Programming (OOP)Beginner24 min read
Constructors, this Keyword & static Members
Use default and parameterized constructors, constructor chaining with this(), static variables, static methods, and static initialization blocks.
Key Takeaways & Core Concepts
- Constructor Chaining (`this(...)`): Calls another constructor in the same class and must be the first statement.
- Static Fields: Shared across all instances of the class (one copy per class).
- Static Methods: Belong to the class, called via
ClassName.method(), and cannot referencethis,super, or instance fields directly. - Static Initialization Blocks:
static { ... }executes once when the class is first loaded by the JVM—ideal for one-time lookup table setup.
Constructors & Initialization Lifecycle
A constructor runs automatically when new ClassName(...) is called to guarantee every object starts in a valid state.
- Same name as the class, no return type (not even
void). - If you define no constructors, Java supplies a default no-arg constructor. As soon as you define any constructor, the compiler stops generating the default no-arg constructor.
- Constructor Chaining (`this(...)`): Calls another constructor in the same class and must be the first statement.
Constructor Chaining & Static Block
1class User {
2 static int totalUsers;
3 static {
4 totalUsers = 0; // Static initialization block
5 }
6
7 String name;
8 String role;
9
10 User(String name) {
11 this(name, "Student"); // Constructor chaining
12 }
13
14 User(String name, String role) {
15 this.name = name;
16 this.role = role;
17 totalUsers++;
18 }
19}
20
21public class Main {
22 public static void main(String[] args) {
23 User u1 = new User("Ananya");
24 User u2 = new User("Vikram", "Mentor");
25 System.out.println(u1.name + " - " + u1.role);
26 System.out.println(u2.name + " - " + u2.role);
27 System.out.println("Total users: " + User.totalUsers);
28 }
29}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
29 lines
Note: `this(name, "Student")` avoids duplicating initialization logic across overloaded constructors.
The static Keyword
- Static Fields: Shared across all instances of the class (one copy per class).
- Static Methods: Belong to the class, called via
ClassName.method(), and cannot referencethis,super, or instance fields directly. - Static Initialization Blocks:
static { ... }executes once when the class is first loaded by the JVM—ideal for one-time lookup table setup.
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)