java_封装


如何实现封装

将状态私有化 (在状态前加private)

提供获取状态的方法 (public的get方法)

提供修改状态的方法 (public的set方法)

class Bicycle {
    // 状态
    private int cadence = 0;  //将状态私有化
	
    // 行为
    public int getCadence() {  // 提供获取状态的方法
        return cadence;
    }
    
    public void setCadence(int cadence) {  // 提供可以修改状态的方法
        this.cadence = cadence;
    }
}

IDEA编写代码工具: Alt + Insert 然后选择 "Getter and Setter",会自动为每个状态写出 get 和 set 方法

posted @ 2023-08-12 17:10  liudelantu  阅读(14)  评论(0)    收藏  举报