在Java中,protected是一个访问修饰符,它可以用来修饰类的成员(包括变量、方法和内部类)。protected修饰的成员具有以下访问规则:
同一个包内:如果一个类的成员被声明为protected,那么在同一个包内的其他类可以直接访问这个成员。
不同包内:如果一个类的成员被声明为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;
public class SamePackageClass {
public void accessProtectedMembers() {
ProtectedExample example = new ProtectedExample();
System.out.println(example.protectedVar); // 可以直接访问
example.protectedMethod(); // 可以直接访问
}
}
// 文件名:DifferentPackageSubclass.java
package com.different;
import com.example.ProtectedExample;
public class DifferentPackageSubclass extends ProtectedExample {
public void accessProtectedMembers() {
System.out.println(protectedVar); // 可以直接访问,因为它是子类
protectedMethod(); // 可以直接访问,因为它是子类
}
}
// 文件名:DifferentPackageNonSubclass.java
package com.different;
import com.example.ProtectedExample;
public class DifferentPackageNonSubclass {
public void accessProtectedMembers() {
ProtectedExample example = new ProtectedExample();
// System.out.println(example.protectedVar); // 编译错误,无法直接访问
// example.protectedMethod(); // 编译错误,无法直接访问
}
}
总结一下,protected成员可以在同一个包内的其他类中直接访问,也可以在不同包内的子类中直接访问。但是,在不同包内的非子类中无法直接访问protected成员。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。