访问修饰符
小于 1 分钟
访问修饰符
介绍
java 提供四种访问控制修饰符号,用于控制方法和属性( 成员变量 ) 的访问权限( 范围 )
- 公开级别: 用 public 修饰,对外公开
- 受保护级别: 用 protected 修饰,对子类和同一个包中的类公开
- 默认级别: 没有修饰符号,向同一个包的类公开
- 私有级别: 用 private 修饰,只有类本身可以访问,不对外公开
演示
public class Test {
int n3 = 30;
public int n1 = 10;
protected int n2 = 20;
private int n4 =40;
public void setN1() {
// 同类中 访问四个属性
System.out.println(this.n1);
System.out.println(this.n2);
System.out.println(this.n3);
System.out.println(this.n4);
}
}