1. 访问修饰符对类的访问权限
- public:
- 可以被任何其他类访问。也就是说,只要在同一个项目或可访问的类路径下,任何类都能引用该
public
类。
- 例如:
// 在 com.example.demo 包下
package com.example.demo;
public class PublicClass {
// 类的具体内容
}
package com.example.other;
import com.example.demo.PublicClass;
public class AnotherClass {
PublicClass publicClass = new PublicClass();
}
- private:
- 不能修饰类(顶级类,即类定义没有嵌套在其他类中)。如果尝试用
private
修饰顶级类,会导致编译错误。
- protected:
- 同样不能修饰顶级类。尝试用
protected
修饰顶级类也会导致编译错误。
2. 访问修饰符对类成员(属性和方法)的访问权限
- public:
- 类的
public
成员(属性和方法)可以被任何其他类访问,无论该类与定义public
成员的类是否在同一个包中,也无论是否存在继承关系。
- 例如:
package com.example.demo;
public class PublicMemberClass {
public int publicField = 10;
public void publicMethod() {
System.out.println("This is a public method");
}
}
package com.example.other;
import com.example.demo.PublicMemberClass;
public class AccessPublicMember {
public static void main(String[] args) {
PublicMemberClass obj = new PublicMemberClass();
System.out.println(obj.publicField);
obj.publicMethod();
}
}
- private:
private
成员只能在定义它们的类内部被访问。其他类,即使在同一个包中,也无法访问private
成员。
- 例如:
package com.example.demo;
public class PrivateMemberClass {
private int privateField = 20;
private void privateMethod() {
System.out.println("This is a private method");
}
public void accessPrivateMembers() {
System.out.println(privateField);
privateMethod();
}
}
package com.example.other;
import com.example.demo.PrivateMemberClass;
public class TryAccessPrivate {
public static void main(String[] args) {
PrivateMemberClass obj = new PrivateMemberClass();
// 以下两行代码会导致编译错误
// System.out.println(obj.privateField);
// obj.privateMethod();
}
}
- protected:
- 在同一个包内,
protected
成员可以被任何类访问,就像public
成员一样。
- 在不同包中,只有子类可以访问
protected
成员。
- 例如,在
com.example.demo
包下:
package com.example.demo;
public class ProtectedMemberClass {
protected int protectedField = 30;
protected void protectedMethod() {
System.out.println("This is a protected method");
}
}
package com.example.demo;
public class AccessProtectedInSamePackage {
public static void main(String[] args) {
ProtectedMemberClass obj = new ProtectedMemberClass();
System.out.println(obj.protectedField);
obj.protectedMethod();
}
}
- 在不同包
com.example.other
下的子类访问:
package com.example.other;
import com.example.demo.ProtectedMemberClass;
public class SubClassOfProtected extends ProtectedMemberClass {
public void accessProtectedFromSubclass() {
System.out.println(protectedField);
protectedMethod();
}
}
- 在不同包
com.example.other
下的非子类访问会编译错误:
package com.example.other;
import com.example.demo.ProtectedMemberClass;
public class TryAccessProtectedNotSubclass {
public static void main(String[] args) {
ProtectedMemberClass obj = new ProtectedMemberClass();
// 以下两行代码会导致编译错误
// System.out.println(obj.protectedField);
// obj.protectedMethod();
}
}