目录
一、访问修饰符
Java提供了四种访问控制修饰符号,用于控制方法和属性(成员变量)的访问权限(范围)。
1、公开的(public):对外公开。
2、受保护(protected):对子类和同一包中的类公开
3、默认:没有修饰符号,向同一个包的类公开
4、私有(private):只有类本身可以访问,不对外公开
二、封装
把抽象出的数据[属性]和对数据的操作[方法]封装在一起,数据被保护在内部,程序的其它部分只有通过被授权的操作[方法],才能对数据进行操作。
封装的好处:1、隐藏实现细节 2、可以对数据进行验证,保证安全合理。
封装的实现步骤:1、将属性进行私有化(private) 2、提供一个公共的(public)set方法,用于对属性判断并赋值 3、提供一个公共的(public)get方法,用于获取属性的值。
示例代码:
public class Encapsulation01 {
public static void main(String[] args) {
Person person = new Person();
person.setName("小明");
person.setAge(1200);
person.setSalary(5600);
person.info();
}
}
class Person{
public String name;
private int age;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
if (name.length()>= 2 && name.length() <= 6){
this.name = name;
}else {
System.out.println("你的名字过长或过短");
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
//加入判断逻辑
if (age >= 1 && age <= 120){
this.age = age;
}else {
System.out.println("请输入正确的年龄");
}
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
//提供一个方法对外展示综合信息
public void info(){
System.out.println("姓名:"+name+"\t年龄:"+age+"\t工资"+salary);
}
}
构造器:在给属性赋值时能通过构造器绕过
解决办法:
public Person(String name, int age, double salary) {
//在构造器中使用set方法
setName(name);
setAge(age);
setSalary(salary);
}
三、参考案例
创建程序,在其中定义两个类:Account和AccountTest类体会Java的封装性。
1. Account类要求具有属性:姓名(长度为2位3位或4位)、余额(必须>20)、密码(必须是六位),如果不满足,则给出提示信息,并给默认值。
2.通过setXxx的方法给Account的属性赋值。
3.在AccountTest中测试。
Account类
public class Account {
private String name;
private double balance;
private String password;
public Account() {
}
//在构造器中调用set方法,防止跳过属性赋值检查
public Account(String name, double balance, String password) {
setName(name);
setBalance(balance);
setPassword(password);
}
public String getName() {
return name;
}
public void setName(String name) {
if (name.length()>= 2 && name.length() <= 4){
this.name = name;
} else {
System.out.println("请输入2~4长度的名字");
this.name = "张三";
}
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
if (balance > 20){
this.balance = balance;
} else {
System.out.println("余额不足");
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
if (password.length() == 6) {
this.password = password;
}else {
System.out.println("密码长度为六位");
this.password = "000000";
}
}
}
AccountTest类
public class AccountTest {
public static void main(String[] args) {
Account account = new Account("老王", 100, "666666");
System.out.println(account.getName());
System.out.println(account.getBalance());
System.out.println(account.getPassword());
}
}