官方定义:一种将抽象性函式接口的实作细节部份包装、隐藏起来的方法。封装可以被认为是一个保护屏障,防止该类的代码和数
据被外部类定义的代码随机访问。
大白话定义:通过getter和setter方法访问私有的在成员变量。
功能:
1、更容易修改自己的实现代码,而不用修改那些调用我们代码的程序片段。
eg. 把下列age类型从 int 改成 String。
1 class Husband{ 2 public int age; 3 public String name; 4 } 5 6 class Wife{ 7 private int age; 8 private String name; 9 10 void setAge(int age){ 11 this.age = age; 12 } 13 14 void setName(String name){ 15 this.name = name; 16 } 17 18 int getAge(){ 19 return age; 20 } 21 22 String getName(){ 23 return name; 24 } 25 26 } 27 28 29 public class TestEncapsulation { 30 public static void main(String[] args) { 31 Husband h1 = new Husband(); 32 h1.age = 21; 33 h1.name = "a1"; 34 35 Husband h2 = new Husband(); 36 h2.age = 22; 37 h2.name = "a2"; 38 39 40 Wife w1 = new Wife(); 41 w1.setAge(18); 42 w1.getAge(); 43 44 Wife w2 = new Wife(); 45 w2.setAge(19); 46 w2.getAge(); 47 48 49 50 System.out.println(h1.age); 51 System.out.println(w2.getAge()); 52 53 } 54 }
改:Husband 类 要改外设调用程序;Wife 类需内改动。同时,假设有100个Husband对象和100个Wife对象,显然改Wife 类要容易。
1 class Husband{ 2 public String age; // 改成 String 3 public String name; 4 } 5 6 class Wife{ 7 private String age; // 改成 String 8 private String name; 9 10 void setAge(int age){ 11 this.age = String.valueOf(age); 12 } 13 14 void setName(String name){ 15 this.name = name; 16 } 17 18 String getAge(){ // 改成 String 19 return age; 20 } 21 22 String getName(){ 23 return name; 24 } 25 26 } 27 28 29 public class TestEncapsulation { 30 public static void main(String[] args) { 31 Husband h1 = new Husband(); 32 h1.age = “21”; // 改调用程序 33 h1.name = "a1"; 34 35 Husband h2 = new Husband(); 36 h2.age = "22"; 37 h2.name = "a2"; 38 39 40 Wife w1 = new Wife(); 41 w1.setAge(18); 42 w1.getAge(); 43 44 Wife w2 = new Wife(); 45 w2.setAge(19); 46 w2.getAge(); 47 48 49 50 System.out.println(h1.age); 51 System.out.println(w2.getAge()); 52 53 } 54 }
时间: 2024-10-02 05:21:51