封装的概念和特点
- 将类的某些信息隐藏在类内部,不允许外部程序直接访问
- 通过该类提供的方法来实现对隐藏信息的操作和访问
- 隐藏对象的信息
- 留出访问的接口
- 特点:
- 只能通过规定的方法访问数据
- 隐藏类的实例细节,方便修改和实现
封装的代码实现(上)
- 实现步骤
封装的代码实现(下)
- 案例:
public class Book {
//私有属性:书名、作者、出版社、价格
private String name,author,publisher;
private double price;
//通过构造方法实现属性赋值
public Book(String name,String author,String publisher,double price){
this.name=name;
this.author=author;
this.setPublisher(publisher);
this.setPrice(price);
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
public String getName(){
return this.name;
}
public String getAuthor(){
return this.author;
}
public void setPublisher(String publisher){
this.publisher=publisher;
}
public String getPublisher(){
return this.publisher;
}
public void setPrice(double price){
if(price>10){
this.price=price;
}else{
System.out.println("图书价格最低10元");
this.price=10;
}
}
public double getPrice(){
return this.price;
}
//信息介绍方法,描述图书所有信息
public void message(){
System.out.println("书名:"+this.getName());
System.out.println("作者:"+this.getAuthor());
System.out.println("出版社:"+this.getPublisher());
System.out.println("价格:"+this.getPrice()+"元");
}
}
public class BookTest {
// 测试方法
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
Book sy1=new Book("红楼梦","曹雪芹","人们文学出版社",-2);
Book sy2=new Book("小李飞刀","古龙","中国长安出版社",55.5);
sy1.message();
System.out.println("========================");
sy2.message();
}
}
使用包进行类管理
- 包的作用
- 管理java文件
- 解决同名文件冲突
- 包的语法
- package 包名;
- 例:
package com.imooc.animal;
- 注意:
- 必须放在java源文件中的第一行
- 一个java源文件中只能有一个package语句
- 包名全部英文小写
- 命名方式:域名倒序+模块+功能
- 包的导入
- import 包名.类名;
- 例:
- 导入包中全部类:
import com.imooc.*;
- 导入包中指定类:
import com.imooc.animal.Cat;
案例总结
public class UserManager {
public String checkUser(User one, User two) {
// 判断用户名是否为空,是否一致
String str = "";
if(one.getName() != null && two.getName()!=null) {
if(one.getName().equals(two.getName())) {
str = "用户名一致";
if(one.getPassword() != null && two.getPassword()!= null) {
if(one.getPassword().equals(two.getPassword())) {
str += "密码一致";
return str;
}else {
str += "密码不一致";
return str;
}
}else {
str = "密码不能为空";
return str;
}
}else {
str = "用户名不一致";
return str;
}
}else {
str = "用户名不能为空";
return str;
}
}
}
public class User {
private String name;
private String password;
User(String name,String password){
this.setName(name);
this.setPassword(password);
}
public String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
private void setPassword(String password) {
this.password = password;
}
public void show() {
System.out.println("用户名:"+ this.name);
System.out.println("用户名:"+ this.password);
}
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserManager use = new UserManager();
User a = new User("Lucy","123456");
User b = new User("Mike","123456");
a.show();
b.show();
System.out.println("===================");
System.out.println(use.checkUser(a, b));
}
}