Java封装
1.什么是封装
封装可以认为是一个保护屏障,防止代码和数据被外部类定义的代码随机访问。封装最主要的功能在于我们可以修改自己的实现代码,而不用修改那些调用我们代码的程序片段。封装加强了代码的安全性。
2.封装的优点
1.良好的封装能够减少耦合性
2.类内部的结构可以自由修改 3.隐藏信息,增强安全性3.实现封装的步骤
- 修改属性的可见性来限制对属性的访问private
public class Person { private String name; private int age;}复制代码
2.对每个值属性提供对外的公共方法访问,使用get,set方法
public class Person{ private String name; private int age; public int getAge(){ return age; } public String getName(){ return name; } public void setAge(int age){ this.age = age; } public void setName(String name){ this.name = name; }}复制代码
代码实例
public class Dog { // 静态变量 private String name; private int health;// 健康值 private int love; private String strain;// 宠物的品种 public void show() { System.out.println("我叫" + name + ",现在健康值是:" + health + ",亲密度是:" + love + ",品种是:" + strain); } public Dog() { } public Dog(int health, int love, String strain) { this.health = health; this.love = love; this.strain = strain; } // 不能够轻易的可以通过对象名.属性名来修改数据 只提供一个方法给他 具体参数合法性判断由我们自己来决定 public void setHealth(int health) { if (health < 0 || health > 100) { System.out.println("健康值是0-100,默认值是60"); this.health = 60; return; } this.health = health; } public int getHealth() { return this.health; } public void setName(String name) { this.name = name; } public String getName() { return this.name; }}复制代码
public class Demo02 { public static void main(String[] args) { // TODO Auto-generated method stub Dog dog = new Dog(); // 封装属性 外部观察不到 只能看到相对应的方法 并且可以在方法里面实现控制 dog.setHealth(1001); dog.setName("哈哈"); System.out.println(dog.getName()); System.out.println(dog.getHealth()); // 没有封装属性 可以随意的查看对象的属性 Dog2 dog2 = new Dog2(); dog2.health = -100; dog2.show(); }}复制代码
public class Demo01 { public static void main(String[] args) { // TODO Auto-generated method stub // 人有姓名 年龄 身高 体重 使用封装思想来创建类 Person person = new Person(); person.setName("张三"); person.setAge(18); person.setHeight(175); person.setWeight(130); System.out.println(person.toString()); }}class Person { private String name; private int age; private int height; private int weight; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getHeight() { return height; } public void setHeight(int height) { if (height < 0) { this.height = 0; return; } this.height = height; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", height=" + height + ", weight=" + weight + "]"; } public int getWeight() { return weight; } public void setWeight(int weight) { if (weight < 0) { this.weight = 0; return; } this.weight = weight; }}复制代码