Java protected
Created By: chatGPT
Java's
protected
keyword is an access modifier that allows a member (variable or method) to be accessible within its own package and by subclasses. This is particularly useful in object-oriented programming, where we want to encapsulate the data while still allowing certain classes to access it.class Animal {
protected String sound;
protected void makeSound() {
System.out.println(sound);
}
}
class Dog extends Animal {
public Dog() {
sound = "Bark";
}
public void bark() {
makeSound(); // Accessing protected method
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.bark(); // Outputs: Bark
}
}
In the example above, the
Animal
class has a protected variable sound
and a protected method makeSound()
. The Dog
class, which is a subclass of Animal
, can access both of these members. This access control is beneficial when we want to ensure that only related classes can access certain properties and behaviors.class Cat extends Animal {
public Cat() {
sound = "Meow";
}
public void meow() {
makeSound(); // Accessing protected method
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.meow(); // Outputs: Meow
}
}
When designing your class structure, remember that using
protected
is a balance between accessibility and encapsulation. It allows controlled access to sensitive parts of your class hierarchy, providing a level of safety while still being flexible.class Base {
protected int value;
protected Base(int value) {
this.value = value;
}
}
class Derived extends Base {
public Derived(int value) {
super(value);
}
public void display() {
System.out.println("Value: " + value);
}
}
public class Main {
public static void main(String[] args) {
Derived obj = new Derived(10);
obj.display(); // Outputs: Value: 10
}
}