Java 权限修饰符 public、protected、(缺省)、private 置于类的成员定义前,用来限定对象对该类成员的访问权限。
对于 class 的权限修饰符只可以用 public 和 default(缺省)
- public 类可以在任意地方被访问
- default 类只可以被同一个包内部的类访问
修饰符 | 类内部 | 同一个包 | 不同包的子类 | 同一个工程 |
---|---|---|---|---|
private | yes | |||
(缺省) | yes | yes | ||
protected | yes | yes | yes | |
public | yes | yes | yes | yes |
例子
Order.java
package com.klvchen.java2;
public class Order {
private int orderPrivate;
int orderDefault;
protected int orderProtected;
public int orderPublic;
private void methodPrivate() {
orderPrivate = 1;
orderDefault = 2;
orderProtected = 3;
orderPublic = 4;
}
void methodDefault() {
orderPrivate = 1;
orderDefault = 2;
orderProtected = 3;
orderPublic = 4;
}
protected void methodProtected() {
orderPrivate = 1;
orderDefault = 2;
orderProtected = 3;
orderPublic = 4;
}
public void methodPublic() {
orderPrivate = 1;
orderDefault = 2;
orderProtected = 3;
orderPublic = 4;
}
}
OrderTest.java
package com.klvchen.java2;
public class OrderTest {
public static void main(String[] args) {
Order order = new Order();
order.orderDefault = 1;
order.orderProtected = 2;
order.orderPublic = 3;
order.methodDefault();
order.methodProtected();
order.methodPublic();
// 同一个包中的其他类,不可以调用Order类中私有的属性,方法
// order.orderPrivate = 4;
// order.methodPrivate();
}
}
SubOrder.java
package com.klvchen.java3;
import com.klvchen.java2.Order;
public class SubOrder extends Order {
public void method() {
orderProtected = 1;
orderPublic = 2;
methodProtected();
methodPublic();
// 在不同包的子类中,不能调用Order类中声明为 private 和 缺省权限的属性、方法
// orderPrivate = 3;
// orderDefault = 4;
// methodPrivate();
// methodDefault();
}
}
OrderTest.java
package com.klvchen.java3;
import com.klvchen.java2.Order;
public class OrderTest {
public static void main(String[] args) {
Order order = new Order();
order.orderPublic = 1;
order.methodPublic();
//不同包下的普通类(非子类)要使用Order类, 不可以调用声明为 private, 缺省, protected权限的属性,方法
// order.orderPrivate = 2;
// order.orderDefault = 3;
// order.orderProtected = 4;
// order.methodPrivate();
// order.methodDefault();
// order.methodProtected();
}
}