private关键字使用

1. private关键字的作用:

1. 用于封装属性为私有属相, 使得其不能在被对象或类名调用到
2. 要调用private封装的属相, 需要定义对应的get和set方法


6.

public class ClassTest {

    public static void main(String[] args) {
        System.out.println("main......");
        Quzq obj = new Quzq();
        System.out.println(obj.x);    // 这里访问不了, 会报错
        System.out.println(Quzq.y);   // 同上, 因这两个属相都使用private封装过了
    }

}


class Quzq {
    private int x = 1;
    private static int y =2;
    
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public static int getY() {
        return y;
    }
    public static void setY(int y) {
        Quzq.y = y;
    }
}
原文地址:https://www.cnblogs.com/quzq/p/13681034.html