1、封装是什么?以及为什么要进行封装?
通常情况下可以给成员变量赋值一些合法但不合理的数值,这种情况在编译阶段和运行阶段都不会报错或给出任何的提示信息,此数值虽然合法但与现实生活不符;为了避免上述问题的发生,就需要对成员变量进行密封包装处理来保证该成员变量的合法合理性,这种机制就叫做封装。封装可以被认为是一个保护屏障,防止该类的代码和数据被外部类定义的代码随机访问。要访问该类的代码和数据,必须通过严格的接口控制。
2、如何进行封装?
(1)私有化成员变量,使用private关键字修饰;
(2)提供公有的get和set方法,在方法体中进行合理值的判断,使用public关键字修饰;
(3)在构造方法中使用set方法进行合理值的判断;
3、事例如下/*person.java*/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
/* 编程实现person类的封装 */ public class person{ //1.私有化成员变量,使用private关键字修饰 private string name; private int age; private string country; //使用static关键字修饰成员变量表示提升为类层级只有一份被所有对象共享 //public static string country;
//3.在构造方法中调用set方法进行合理值的判断 public person(){ } public person(string name, int age, string country){ setname(name); setage(age); setcountry(country); }
//2.提供公有的get和set方法,在方法体中进行合理值的判断 public string getname(){ return name; } public void setname(string name){ this .name = name; } public int getage(){ return age; } public void setage( int age){ if (age > 0 && age < 150 ){ this .age = age; } else { system.out.println( "年龄不合理!!!" ); } } public string getcountry(){ return country; } public void setcountry(string country){ this .country = country; }
public void show(){ system.out.println( "我是" + getname() + ",今年" + getage() + "岁了,来自" + getcountry() + "!" ); }
//自定义成员方法描述吃饭的行为 public void eat(string food){ system.out.println(food + "真好吃!" ); } //自定义成员方法描述娱乐的行为 public void play(string game){ system.out.println(game + "真好玩!" ); } } |