封装
大约 2 分钟
将类的某些信息隐藏在类内部,不允许外部程序直接访问
特点
- 隐藏对象的信息,留出访问的接口,只能通过规定的方法访问和操作数据
- 隐藏类的实例细节,方便修改和实现
访问修饰符
private
:私有的,只允许在本类中进行访问默认
:允许在当前类、同包子类/同包非子类访问,跨包子类/跨包非子类不允许访问protected
:受保护的, 允许在本类、同包子类/同包非子类、跨包子类进行访问,跨包非子类不允许public
:共有的,允许在任意位置访问
访问修饰符 | 本类 | 同包 | 子类 | 其他 |
---|---|---|---|---|
private | ✅ | ❌ | ❌ | ❌ |
默认 | ✅ | ✅ | ❌ | ❌ |
protected | ✅ | ✅ | ✅ | ❌ |
public | ✅ | ✅ | ✅ | ✅ |
实现步骤
修改属性的可见性(访问修饰符)
创建
getter/setter
方法(设为 public 用于属性的读写)在
getter/setter
方法中加入属性控制语句(对属性值的合法性进行判断)
// Book.java
public class Book {
//私有属性:书名、作者、出版社、价格
private String bookName;
private String author;
private String publisher;
private float price;
//通过构造方法实现属性赋值
public Book() {
}
public Book(String bookName, String author, String publisher, float price) {
this.bookName = bookName;
this.author = author;
this.setPublisher(publisher);
this.setPrice(price);
}
/**
* 通过公有的get/set方法实现属性的访问,其中:
* 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
* 2、限定作者、书名均为只读属性
*/
public String getBookName() {
return bookName;
}
public String getAuthor() {
return author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
if (price < 10) {
price = 10;
System.out.println("图书价格最低10元");
}
this.price = price;
}
//信息介绍方法,描述图书所有信息
public void description() {
System.out.println("书名:" + this.getBookName());
System.out.println("坐着:" + this.getAuthor());
System.out.println("出版社:" + this.getPublisher());
System.out.println("价格:" + this.getPrice() + "元");
}
}
// BookTest.java
public class BookTest {
// 测试方法
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
Book book1 = new Book("红楼梦","曹雪芹","人民文学出版社",10.0f);
Book book2 = new Book("小李飞刀","古龙","人民长安出版社",55.5f);
book1.description();
System.out.println("=======================");
book2.description();
}
}