封装,是将类的某些信息隐藏在类内部,不允许外部程序直接访问。
通过该类提供的方法来实现对隐藏信息的操作和访问,作用:①隐藏对象的信息;②留出访问的接口。
1)只能通过规定的方法访问数据;
2)隐藏类的实例细节,方便修改和实现。
修改属性的可见性 —— 设为private
创建getter/setter方法 —— 设为public 用于属性的读写
在getter/setter方法中加入属性控制语句 —— 对属性值的合法性进行判断
package com.pino.animal; public class Cat { //成员属性:昵称、年龄、体重、品种 //修改属性的可见性——private 限定只能在当前类内访问 private String name; //String类型默认值为null private int month; // int 类型默认值为0 private double weight; //double 类型默认值为0.0 private String species; public Cat() { System.out.println("调用了无参构造方法"); } public Cat(String name, int month, double weight, String species) { this.name = name; this.month = month; this.weight = weight; this.species = species; } //创建get/set方法,在get/set方法中添加对属性的限定 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMonth() { return month; } public void setMonth(int month) { if (month <= 0) { System.out.println("输入信息错误"); } else { this.month = month; } } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } } package com.pino.animal; public class CatTest { public static void main(String[] args) { //对象实例化 Cat one = new Cat(); one.setName("乐乐"); one.setMonth(3); one.setWeight(11.0); one.setSpecies("短尾猫"); //Cat one = new Cat("乐乐", 3, 11.0, "波斯猫"); System.out.println("昵称:"+one.getName()); System.out.println("年龄:"+one.getMonth()); System.out.println("体重"+one.getWeight()); System.out.println("品种:"+one.getSpecies()); } }