java protected
时间: 2023-10-14 21:29:35 浏览: 34
The protected keyword in Java is an access modifier that provides access to the member variables and methods of a class to its subclasses and classes within the same package.
When a class member is marked as protected, it can only be accessed within the same package or by a subclass of the class. Protected members are useful when you want to provide access to certain fields or methods of a class to its subclasses, but not to other classes outside the package.
For example, if we have a class called Animal, and we want to provide access to its protected member variable called age to its subclass called Dog, we can declare the variable as protected in the Animal class like this:
```
public class Animal {
protected int age;
}
```
Now, the Dog class can access the age variable like this:
```
public class Dog extends Animal {
public void printAge() {
System.out.println("The age of this dog is: " + age);
}
}
```
Protected members can also be accessed within the same class, just like private members. However, unlike private members, protected members can be accessed by subclasses as well.
It is important to note that the protected access modifier is less restrictive than the private access modifier, but more restrictive than the public access modifier.