Java protected Members in Inheritance

In Java, the protected access modifier is used to specify that a member (a field or a method) of a class is accessible within the class and its subclasses. This means that a protected member can be accessed by any class that extends the class in which the protected member is defined, including classes in other packages.

Here's an example of how the protected keyword can be used in Java inheritance:

package com.example;

public class Animal {
    protected String name;

    protected void setName(String name) {
        this.name = name;
    }
}

package com.example;

public class Dog extends Animal {
    public void speak() {
        System.out.println(name + " says woof!");
    }
}

package com.example;

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.setName("Buddy");
        myDog.speak(); // prints "Buddy says woof!"
    }
}
S‮o‬urce:www.theitroad.com

In this example, the Animal class defines a protected field called name and a protected method called setName(). The Dog class extends the Animal class and is able to access the name field using the protected access modifier. The Main class creates an instance of the Dog class, sets its name using the setName() method, and calls its speak() method, which accesses the name field.

Using the protected access modifier can be useful when you want to provide access to certain members of a class to its subclasses, but not to other classes outside the class hierarchy. However, it's important to use the protected access modifier carefully, as it can lead to more tightly-coupled code that is harder to maintain and modify.