第一节 封装(Encapsulation)
1. 什么是封装
封装就是将类的部分属性和方法隐藏起来,不允许外部程序直接访问,只能通过该类提供的公开的方法来访问类中定义的属性和方法。封装是面向对象的三大特征之一。
2.如何使用封装
示例
public class Person {public String name ; // 姓名public int age ; // 年龄public String secret ; // 秘密public Person ( String name , int age , String secret ){this . name = name ;this . age = age ;this . secret = secret ;}}
修改属性的可见性:将类中定义的所有属性全部修改为private修饰
public class Person {private String name ; // 姓名//private表示私有的意思 相当于个人隐私private int age ; // 年龄private String secret ; // 秘密public Person ( String name , int age , String secret ){this . name = name ;this . age = age ;this . secret = secret ;}}
创建公开的 getter/setter 方法:用于读取 / 修改属性值
public class Person {private String name ; // 姓名//private表示私有的意思 相当于个人隐私private int age ; // 年龄private String secret ; // 秘密public Person ( String name , int age , String secret ){this . name = name ;this . age = age ;this . secret = secret ;}//ALT + INSERTpublic 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 String getSecret () {return secret ;}public void setSecret ( String secret ) {this . secret = secret ;}}
在 getter/setter 方法中加入控制语句:用于对属性值的合法性校验
public void setAge ( int age ) {if ( age < 0 ){System . out . println ( " 你输入的年龄不合法,年龄必须为 > 0 的整数 " );} else {this . age = age ;}}
3. 为什么要使用封装
a. 封装提高了代码的重用性。因为封装会提供对外访问的公开的方法,而方法可以重用,因此封装提高了代码的重用性。
b. 封装提高了代码的可维护性。修改代码时,只需要修改部分代码,但不会影响其他代码。比如:年龄在设计时只考虑到了负数的情况,没有考虑实际生活中的情况,人的年龄一般都不会超过200岁,因此还需要加上一层验证。
public void setAge ( int age ) {if ( age < 0 || age > 200 ){System . out . println ( " 你输入的年龄不合法,年龄必须为 0 ~ 200 之间的整数 " );} else {this . age = age ;}}
c. 封装隐藏了类的具体实现细节,保护了代码实现逻辑。