在Java中,访问修饰符(Access Modifiers)用于控制类、变量、方法和构造函数的访问级别。protected是其中之一,它提供了一种介于public和private之间的访问级别。
protected修饰的成员(变量、方法或构造函数)在同一个包内的其他类中是可见的。protected成员,那么子类可以访问这些protected成员,即使它们不在同一个包中。// 文件名:ProtectedExample.java
package com.example;
public class ProtectedExample {
protected int protectedVar = 10;
protected void protectedMethod() {
System.out.println("This is a protected method.");
}
}
// 文件名:SamePackageClass.java
package com.example;
class SamePackageClass {
void accessProtectedMembers() {
ProtectedExample example = new ProtectedExample();
System.out.println(example.protectedVar); // 可以访问
example.protectedMethod(); // 可以访问
}
}
// 文件名:ParentClass.java
package com.example.parent;
public class ParentClass {
protected int protectedVar = 20;
protected void protectedMethod() {
System.out.println("This is a protected method in ParentClass.");
}
}
// 文件名:ChildClass.java
package com.example.child;
import com.example.parent.ParentClass;
class ChildClass extends ParentClass {
void accessProtectedMembers() {
System.out.println(protectedVar); // 可以访问,因为ChildClass继承了ParentClass
protectedMethod(); // 可以访问,因为ChildClass继承了ParentClass
}
}
protected修饰符不能用于修饰类(外部类),只能用于修饰类的成员(变量、方法或构造函数)。protected,那么它的子类(无论是否在同一包中)都可以访问这个成员。protected修饰符提供了一种平衡封装和继承的方式,允许子类访问父类的某些成员,同时仍然保持一定的封装性。总之,protected访问修饰符在Java中用于控制类成员的访问级别,提供了包内可见性和跨包继承可见性两种特性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。