封装
(1)将类的某些信息隐藏在类内部,不允许外部程序直接访问(隐藏的信息)
(2)通过该类提供的方法来实现对隐藏信息的操作和访问(留出访问的接口)
特点:
(1) 只能通过规定的方法访问数据
(2) 隐藏类的实例细节,方便修改和实现
实现步骤:
(1) 修改属性的可见性(设为private)
(2) 创建getter和setter方法(设为public 便于属性的读写)
(3) 在getter和setter方法中添加属性控制语句(对属性的合法性进行判断)
例如:编写自定义类实现图书信息设置
publicclassBookInf {
//静态成员,(1)修改属性的可见性
private String name,author,version;
privatedoubleprice;
//构造方法
public BookInf(String name,String author) {
this.name = name;
this.author = author;
}
//类方法
//(2)创建getter和setter方法
public String getVersion() {
returnversion;
}
public String getName() {
returnname;
}
public String getAuthor() {
returnauthor;
}
publicvoid setVersion(String version) {
this.version = version;
}
publicdouble getPrice() {
returnprice;
}
publicvoid setPrice(doubleprice) {
//(3)添加属性控制语句
if(price<10) {
System.out.println("图书价格最低10元!");
this.price=10;
}
else
this.price = price;
}
}
publicclassBookTest {
publicstaticvoid main(String[] args) {
//实例化对象
BookInfone= newBookInf("红楼梦","曹雪芹");
BookInftwo = newBookInf("小李飞刀","古龙");
//调用静态(类)方法
one.setPrice(8);
one.setVersion("人民文学出版社");
two.setPrice(55.5);
two.setVersion("中国长安出版社");
//输出信息
System.out.println("书名:"+one.getName());
System.out.println("作者:"+one.getAuthor());
System.out.println("出版社:"+one.getVersion());
System.out.println("价格:"+one.getPrice());
System.out.println("=======================");
System.out.println("书名:"+two.getName());
System.out.println("作者:"+two.getAuthor());
System.out.println("出版社:"+two.getVersion());
System.out.println("价格:"+two.getPrice());
}
}