一、封装概念
将类的某些信息隐藏在类的内部,不允许外部程序直接访问,通过该类提供的方法来实现对隐藏信息的操作和访问
例子:ATM机 特点:
1)只能通过规定的方法访问数据
2)隐藏类的实例细节,方便修改和实现
二、实现封装的步骤
1、修改属性的可见性,将访问修饰符设计为private(私有化),当private加在属性前面表示属性只能在当前类内被访问(信息的隐藏)
2、创建getter(取值)/setter(赋值)方法,:设为public 用于属性的读写(留出接口)
3、在getter/setter方法中加入属性控制语句,对合法性进行判断::对属性值的合法性进行判断(留出接口)
private String name; public void setName(String name) { this.name = name; } public String getName() { return "我是一只名叫:" + this.name + "的宠物猫"; }
三、如何快捷的生成封装方法
1)eclipse代码编辑区空白处右键->source->Generate Getters and Setters...
2)idea封装Alt+Insert组合键,或者空白处右键Generate,选择Getter and Setter。
3)只有getXXX方法的属性是只读属性;
4)只有setXXX方法的属性是只写属性 ;
四、编程练习:图书信息设置
package com.fiona.javaBasis.day11fz; public class Book { //私有属性:书名、作者、出版社、价格 private String bookname;//书名,只读 private String author;//作者,只读 private String chubanshe; private double price; //通过构造方法实现属性赋值 public Book(String bookname,String author){ this.bookname=bookname; this.author=author; } /*通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性 */ //信息介绍方法,描述图书所有信息 public String getBookname() { return bookname; } public String getAuthor() { return author; } public String getChubanshe() { return chubanshe; } public void setChubanshe(String chubanshe) { this.chubanshe = chubanshe; } public double getPrice() { return price; } public void setPrice(double price) { if(price<10){ System.out.println("图书价格必须大于10元"); this.price=10; }else { this.price = price; } } }
package com.fiona.javaBasis.day11fz; public class BookTest { // 测试方法 public static void main(String[] args) { //实例化对象,调用相关方法实现运行效果 Book one = new Book("红楼梦","曹雪芹"); one.setChubanshe("人民文学出版社"); one.setPrice(1); Book two = new Book("小李飞刀","古龙" ); two.setChubanshe("中国长安出版社"); two.setPrice(55.5); System.out.println("书名:"+one.getBookname()); System.out.println("作者:"+one.getAuthor()); System.out.println("出版社:"+one.getChubanshe()); System.out.println("价格:"+one.getPrice()); System.out.println("======================="); System.out.println("书名:"+two.getBookname()); System.out.println("作者:"+two.getAuthor()); System.out.println("出版社:"+two.getChubanshe()); System.out.println("价格:"+two.getPrice()); } }