Lesson Completion
Back to course

The `protected` Modifier: For Inheritance

Beginner
10 minutes4.6Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: protected grants access to the same package AND subclasses in any package. It's the "extension point" modifier—use it for methods/fields that subclasses should be able to override or access for customization.

Think of company secrets shared with partners. Only employees (same package) and official partners (subclasses) know them!


2. Conceptual Clarity (The "Simple" Tier)

💡 The Analogy: The Family Recipe

A family recipe:

  • Family members (same package): Can use it
  • Married-in partners (subclasses): Can use it
  • Friends (other packages): Cannot

3. Technical Mastery (The "Deep Dive")

Protected Rules

  1. Same package: Full access
  2. Subclasses (any package): Access through inheritance
  3. Not through reference: Can't access via parent reference from other package

4. Interactive & Applied Code

java
// File: com/example/Parent.java package com.example; public class Parent { protected int value = 100; protected void display() { System.out.println("Parent"); } } // File: com/other/Child.java package com.other; import com.example.Parent; public class Child extends Parent { void test() { value = 200; // ✅ OK (subclass access) display(); // ✅ OK (subclass access) } } // File: com/other/Unrelated.java package com.other; import com.example.Parent; public class Unrelated { void test() { Parent p = new Parent(); // p.value = 100; // ❌ ERROR: Not accessible from another package! } }

5. Interview Corner

The "Killer" Interview Question: "Can you access protected members through a parent reference from another package?" Answer: NO! Protected access for subclasses works through inheritance, not through references:

java
package other; class Child extends Parent { void test(Parent p) { this.value = 10; // ✅ OK (inheritance) p.value = 10; // ❌ ERROR (reference) } }

Pro-Tip: Use protected for template methods that subclasses override!

Topics Covered

Java FundamentalsModularity

Tags

#java#packages#access-modifiers#encapsulation#scope

Last Updated

2025-02-01