What is the access modifier 'protected' in programming languages and when should it be used?
sobes.tech AI
Answer from AI
protected is an access modifier that allows class members (fields, methods) to be accessible within the class itself, within subclasses (even if they are in a different package), and within all classes in the same package.
Usage:
It is used when you want to provide access to class members only to its subclasses and other classes in the same package, hiding them from the outside world beyond this package and inheritance hierarchy.
Examples of use cases:
-
When the parent class contains fields or methods that are part of its internal implementation but are necessary for extending functionality in subclasses.
public class Animal { protected String name; // Accessible to subclasses and classes in the same package protected void eat() { // Accessible to subclasses and classes in the same package System.out.println(name + " is eating."); } } public class Dog extends Animal { public void bark() { System.out.println(name + " is barking."); // Access to protected field name eat(); // Access to protected method eat() } } -
When there is a group of classes in a package that are closely related, and they need to access each other's internal elements but hide these elements from classes in other packages. In this case,
protectedworks similarly to the default modifier (package-private) for classes in the same package, but additionally opens access to subclasses from any package.// Package com.example.core package com.example.core; public class BaseConfig { protected int threshold = 10; // Accessible to classes in com.example.core and subclasses from any package }// Package com.example.app (may be in a different package) package com.example.app; import com.example.core.BaseConfig; public class AppConfig extends BaseConfig { public void displayThreshold() { System.out.println("Threshold: " + threshold); // Access to protected field from another package } }// Package com.example.core package com.example.core; public class RelatedConfig { public void printBaseThreshold(BaseConfig config) { System.out.println("Base Threshold from RelatedConfig: " + config.threshold); // Access to protected field in the same package } }
Avoid excessive use of protected, as it can complicate refactoring and break encapsulation, allowing subclasses or classes in the same package to directly manipulate the internal state of the object. It is preferable to use private with public getter/setter methods if direct inheritance and access to internal implementation are not the main goal.