封装演示代码一
Account.java
package chapter3.oop08;
/**
* 定义一个银行账户类,包含属性:账户名,余额等。并对其中的月进行封装,余额不得小于0.
* 另外定义一个取款方法withdraw,判断取款金额是否合法,另外余额是否充足
*/
public class Account {
/**
* 账号
*/
private String momo;
/**
* 余额
*/
private double balance;
public String getMomo() {
return momo;
}
public void setMomo(String momo) {
this.momo = momo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
if (balance < 0) {
System.out.println("对不起,银行卡余额不能小于0");
return;
}
this.balance = balance;
}
public void withdraw(double money){
//取款金额是否合法
if (money < 0) {
System.out.println("取款金额需要大于0");
return;
}
//程序能执行到这里,说明取款金额是合法的
//继续判断余额够不够
if (this.balance < money) {
System.out.println("对不起余额额不足");
return;
}
//程序执行到这里,说余额充足
this.setBalance(this.getBalance() - money);
System.out.println("取款" + money + "成功");
}
}
AccounbtTest.java
package chapter3.oop08;
public class AccountTest {
public static void main(String[] args) {
//新建账户对象
Account act = new Account();
//给账户属性赋值
act.setMomo("act -001");
act.setBalance(100000);
//读取账户的属性
System.out.println("账号:" + act.getMomo());
System.out.println("余额:" + act.getBalance());
// act.setBalance(-1);
// act.setBalance(0);
//取款
act.withdraw(50000);
System.out.println("余额:" + act.getBalance());
//继续取款
act.withdraw(50000);
System.out.println("余额:" + act.getBalance());
//再取一次
act.withdraw(50000);
System.out.println("余额:" + act.getBalance());
}
}
演示代码输出
封装演示代码二
Employee.java
package chapter3.oop08;
/**
* 定义一个员工类,包含属性:姓名,年龄,工资等。
* 并对其中的工资进行封装,工资不得低于800元。
* 另外定义一个raise方法来涨薪。如果涨薪后的工资超过可10000元,则不再涨薪
*/
public class Employee {
private String name;
private int age;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
if (salary < 800) {
System.out.println("工资不能低于800");
return;
}
this.salary = salary;
}
public void raise(double money){
if((this.salary + money) > 10000){
System.out.println("对不起涨薪失败,因为涨薪后的薪资不能超过一万 : ");
return;
}
//涨薪后的薪资不会超过一万
this.salary = this.salary + money;
System.out.println("涨薪成功");
}
}
EmployeeTest.java
package chapter3.oop08;
public class EmployeeTest {
public static void main(String[] args) {
//创建员工对象
Employee employee = new Employee();
//给属性赋值
employee.setAge(20);
employee.setName("漠漠");
employee.setSalary(9000);
//读取属性的值
System.out.println("姓名 " + employee.getName());
System.out.println("年龄 " + employee.getAge());
System.out.println("薪资 " + employee.getSalary());
//employee.setSalary(700);
employee.raise(1000);
System.out.println("工资:" + employee.getSalary());
employee.raise(200000);
}
}
改不了,工资不能低于800