Methods of Java · Introduction to Java Programming

Protected Specifier

Watch lectures

Protected Specifier

1. Where Protected Sits (beginner)

Access ladder (strict → open): private (self only!) → default (package!) → protected (package + children anywhere!) → public (world!). Protected = "family + neighbours!"

2. Table + Package Proof (exam diagram!)

package zoo;
public class Animal { protected String name = "Leo"; } // protected!
// same package (zoo): ANY class sees name! (like default!)
// other package + child: sees via extends!
package city;
import zoo.Animal;
class Dog extends Animal {
    void show() { System.out.println(name); } // OK! (child anywhere!)
}
class Vet {
    // System.out.println(new Dog().name); // ERROR! (not child, different package!)
}
Modifier Same class Same package Child (other pkg) World
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes (via extends!) No
public Yes Yes Yes Yes

3. Traps

  • Default (no word!) ≠ protected: default blocks outside-package children!
  • Protected field via PARENT ref in child: Animal a = new Animal(); a.name from other package = ERROR (must via this/child ref!).
  • Exam asks "which modifier for library + subclass reuse?" → protected!

4. Exam Points

  • Four-level table + child-outside proof — 5-7 marks, very frequent.
  • Protected vs default — 3-5 marks, favourite distinction.
AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.

← All Introduction to Java Programming modules