Home >Java >javaTutorial >Application of protected access modifier for Java functions
Answer: The protected access modifier allows subclasses and classes in the same package to access the member, while blocking access to classes in other packages. Detailed Description: Protected members are accessible in the defining class, subclasses, and other classes in the same package. Classes in different packages cannot access protected members. Applicable to: a) Allow subclasses to access parent class members. b) Access within the package is allowed, but access outside the package is blocked. For example, the protected method getSpeed() of the parent class Vehicle can be accessed by the subclass Car, but not by the class Truck that is not in the same package.
Java function access modifier: protected
Introduction
In In Java, protected
is an access modifier used to specify restricted access levels for methods, fields, and constructors. It is more restrictive than public
but has looser access than default
.
Semantics
protected
Members can be accessed in the class in which they are defined, in subclasses, and in other classes in the same package . protected
members cannot be accessed. Application
protected
Access permission modifiers are often used in the following situations:
Practical case
Consider a parent classVehicle
, which has a protected
methodgetSpeed ()
. The
public abstract class Vehicle { protected int speed; public void getSpeed() { // ... } }
Car
class is a subclass of Vehicle
and it has access to the getSpeed()
method because it inherits from Vehicle
.
public class Car extends Vehicle { public void displaySpeed() { // 可以访问父类的 protected 方法 getSpeed(); } }
However, the Truck
class is not in the same package as the Vehicle
, so it cannot access the getSpeed()
method.
// Truck 类在一个不同的包中 public class Truck { // 无法访问 Vehicle 中的 protected 方法 // getSpeed(); }
Conclusion
protected
Access modifiers provide a way to restrict access to class members while allowing subclasses and those in the same package access by other classes. It is useful when designing classes with inheritance relationships and restricting access rights in specific packages.
The above is the detailed content of Application of protected access modifier for Java functions. For more information, please follow other related articles on the PHP Chinese website!