java protected
时间: 2023-10-14 18:19:42 浏览: 40
The `protected` keyword in Java is an access modifier that allows a member (method or variable) of a class to be accessed from within the same package or by a subclass of the class in another package.
Here are some important points to note about the `protected` keyword:
- `protected` members are not accessible from outside the package unless they are accessed through a subclass of the class containing the protected member.
- `protected` members can be accessed from within the same package as the class containing the protected member.
- `protected` members can be inherited by a subclass in a different package.
- `protected` members cannot be accessed using class objects, only through an instance of the class or a subclass of the class.
- `protected` members can be accessed from within the same class as the member.
Here is an example of using the `protected` keyword in Java:
```
package com.example.package1;
public class MyClass {
protected int myProtectedVar;
protected void myProtectedMethod() {
// implementation of protected method
}
}
```
```
package com.example.package2;
import com.example.package1.MyClass;
public class MySubClass extends MyClass {
public void myMethod() {
myProtectedVar = 10; // accessing protected variable from subclass
myProtectedMethod(); // accessing protected method from subclass
}
}
```