KTU OOP Java2024 Scheme • 60M ESE
MODULE 1/Section 3: Object-Oriented Programming in Java

Access Modifiers (public, private, protected, default) & the this Keyword

HIGH PRIORITY (Prep Guide)Official Syllabus~16 min study
Official KTU 2024 Syllabus Topics Covered Here
Access modifiers: public, private, protected and default accessthis keyword

1. Topic Introduction

Access modifiers are Java's security guards—controlling which classes can read or modify your fields and methods. Meanwhile, the **this keyword** is an object's self-reference, allowing methods and constructors to resolve variable shadowing, chain constructors cleanly, and pass or return the current object itself.

2. Start From Zero: House Access Locks & Saying 'My Own' (this)

Think of Access Modifiers as 4 privacy locks on data: private = personal diary (only inside YOUR class); default (no keyword) = shared family living room (anyone in the SAME package); protected = family + relatives' kids (same package + subclasses even in other packages); public = public park (everyone!). And what is **this**? Suppose two people in a room are named 'name': a guest parameter (name) and your own personal name (this.name). Saying this.name = name; means 'store the guest's parameter into MY OWN instance variable!'

Key Takeaway: 4 visibility levels (private < default < protected < public). this holds a reference to the current invoking object and also chains constructors via this(...).

3. Essential Exam Definitions

Access Modifiers
Keywords (public, private, protected, or omitted default/package-private) controlling visibility of classes, constructors, fields, and methods across classes and packages.
The this Keyword
An implicit reference variable inside instance methods and constructors that refers to the current object on which the method or constructor was invoked.

4. Detailed Technical Explanation & Syntax

1. The 4 Access Modifiers (Class vs Member Rules)

Top-level non-nested classes can ONLY use public or default (package-private). Class members (fields, methods, constructors, nested classes) can use all four:

  • private: Accessible ONLY within the declaring class itself (invisible even to subclasses!).
  • default (no modifier keyword): Package-private; accessible to all classes and subclasses in the SAME package, invisible outside the package.
  • protected: Accessible to the same class, same package, AND subclasses in DIFFERENT packages (covered with full 4-category table in Module 3!).
  • public: Accessible everywhere from any class in any package.

2. All 6 Uses of the this Keyword (High-Yield Exam Checklist)

Your lecture notes list six distinct ways this is used in Java:

  • 1. Refer to current class instance variable (this.name = name;): Resolves shadowing when local/parameter variables share the same name as instance fields.
  • 2. Invoke current class constructor (this(args);): Constructor chaining to avoid duplicating setup code.
  • 3. Return current class instance (return this;): Enables fluent method chaining (person.setName("A").setAge(20);).
  • 4. Pass current object as an argument in a method call (calc1.addTo(this);).
  • 5. Invoke current class method (this.display();).
  • 6. Pass current object as an argument in another object's constructor (new Helper(this)).

Critical Rules on this

Rule 1: Inside a constructor, this(...) MUST be the very first statement.

Rule 2: A constructor can contain EITHER this(...) OR super(...), never both (because both require line 1!).

Rule 3: this CANNOT be used inside a static method or static block (compile error: non-static variable this cannot be referenced from a static context), because static code runs without any object instance!

5. Working Principle: How Java Resolves Variable Shadowing & this() Chaining

  1. When a parameter name matches field name, Java prioritizes the innermost local scope (name = parameter); this.name jumps directly to the Heap object's field.
  2. When Student() executes this("Unknown", 18); on line 1, Java jumps to Student(String, int), completes it, and returns to execute the remaining lines of Student().

7. Complete Java Code Examples & Tracing

Comprehensive `this` Keyword Demo: Disambiguation, Chaining & Fluent ReturnThisKeywordDemo.java
Demonstrates this resolving shadowed variables, constructor chaining this(...), passing this as a parameter, and returning this for method chaining.
1public class ThisKeywordDemo {
2 private String name;
3 private int score;
4
5 // 1. Constructor chaining using this(...)
6 public ThisKeywordDemo() {
7 this("Guest Student", 0); // MUST be first statement!
8 System.out.println("No-arg constructor finished after chaining.");
9 }
10
11 // 2. Resolving local/parameter shadowing using this.field
12 public ThisKeywordDemo(String name, int score) {
13 this.name = name;
14 this.score = score;
15 }
16
17 // 3. Returning 'this' for fluent method chaining
18 public ThisKeywordDemo setScore(int score) {
19 this.score = score;
20 return this;
21 }
22
23 // 4. Passing 'this' as an argument to another method
24 public void addBonusTo(ThisKeywordDemo target) {
25 target.score += 5;
26 }
27
28 public void boostSelf() {
29 this.addBonusTo(this); // Invokes method & passes current object
30 }
31
32 public void display() {
33 System.out.println(this.name + " -> Score: " + this.score);
34 }
35
36 public static void main(String[] args) {
37 ThisKeywordDemo s1 = new ThisKeywordDemo();
38 s1.setScore(50).boostSelf(); // Fluent method chaining!
39 s1.display();
40
41 ThisKeywordDemo s2 = new ThisKeywordDemo("Diya", 52);
42 s2.display();
43 }
44}
Expected Output
No-arg constructor finished after chaining.
Guest Student -> Score: 55
Diya -> Score: 52
Keywords:thisprivatepublicreturn
Common Exam & Coding Mistakes
  • Writing name = name; inside a constructor (assigns parameter to itself; Heap field stays null!).
  • Calling this(...) after another statement or alongside super(...) inside the same constructor.
  • Using this inside public static void main(...) (compile error!).

Comparison Tables

Java Access Modifiers Quick Summary
ModifierSame ClassSame PackageSubclass (Diff Pkg)World (Other Pkg)
privateYesNoNoNo
default (omitted)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes

Real-World Applications

  • Builder and Fluent APIs across Java libraries return this for readable chained configuration.
  • private fields + public getters/setters implement textbook Encapsulation in every enterprise Java class.

Important KTU Exam Points

  • State the rule: this(...) must be line 1 inside a constructor and cannot coexist with super(...) in the same constructor.
  • Always memorize the 4×4 Access Modifier visibility table—it appears in both Module 1 and Module 3!

Memory Techniques & Revision

  • Access Order (Tightest to Widest): private -> default -> protected -> public ('Please Don't Publish Privates').

Common Pitfalls to Avoid

  • Thinking private members of a superclass are accessible directly in a subclass—they are NOT!

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: The this keyword is an implicit reference inside non-static methods and constructors pointing to the current invoking object.

  • 1. Disambiguate instance variables from shadowed parameters (this.name = name;).
  • 2. Constructor chaining via this(args); (must be the very first statement in a constructor; cannot appear with super()).
  • 3. Return the current instance (return this;) to support fluent method chaining.
  • 4. Pass the current object as an argument (helper.process(this)) or invoke another current-class method (this.display()).
class Student {
String name;
Student() { this("Unknown"); }
Student(String name) { this.name = name; }
}

Quick Understanding Check

1. Why does class Test { int x = 5; static void show() { System.out.println(this.x); } } fail to compile?

2. Can a constructor contain both super() and this(10)?