0
0
Javaprogramming~15 mins

Protected access modifier in Java

Choose your learning style8 modes available
menu_bookIntroduction

The protected access modifier lets you share class members with related classes but keeps them hidden from unrelated ones.

When you want a class member to be accessible in the same package and also in subclasses outside the package.
When you want to allow child classes to use or change a variable or method but keep it hidden from other classes.
When you are designing a class hierarchy and want to share some details only with subclasses.
When you want to control access more than private but less than public.
regular_expressionSyntax
Java
protected dataType variableName;
protected returnType methodName(parameters) {
    // method body
}

The protected keyword is placed before the data type or return type.

Members marked protected are accessible within the same package and by subclasses even if they are in different packages.

emoji_objectsExamples
line_end_arrow_notchA protected integer variable named age.
Java
protected int age;
line_end_arrow_notchA protected method that prints a message.
Java
protected void showName() {
    System.out.println("Name shown");
}
line_end_arrow_notchChild class can access the protected variable message from Parent.
Java
class Parent {
    protected String message = "Hello";
}

class Child extends Parent {
    void printMessage() {
        System.out.println(message); // can access protected member
    }
}
code_blocksSample Program

This program shows a protected variable sound in the Animal class. The Dog class extends Animal and can access sound because it is protected. The makeSound method prints the sound.

Java
class Animal {
    protected String sound = "Some sound";
}

class Dog extends Animal {
    void makeSound() {
        System.out.println(sound);
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.makeSound();
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Protected members are not accessible by unrelated classes outside the package.

line_end_arrow_notch

Use protected when you want to allow subclass access but keep members hidden from other classes.

list_alt_checkSummary

Protected allows access within the same package and subclasses outside the package.

It is more open than private but more restricted than public.

Useful for sharing data or methods with child classes safely.