面向对象中级-封装(案列2)
题目
创建程序,在其中定义两个类:Account和AccountTest类体会Java的封装性。
Account类要求具有属性:姓名(长度为2位3位或4位)、余额(必须>20)、
密码(必须是六位), 如果不满足,则给出提示信息,并给默认值(程序员自己定)
通过setXxx的方法给Account 的属性赋值。
在AccountTest中测试
Account类
package com.hspedu.encap;
import java.util.Scanner;
/**
* 创建程序,在其中定义两个类:Account和AccountTest类体会Java的封装性。
* Account类要求具有属性:姓名(长度为2位3位或4位)、余额(必须>20)、
* 密码(必须是六位), 如果不满足,则给出提示信息,并给默认值(程序员自己定)
* 通过setXxx的方法给Account 的属性赋值。
* 在AccountTest中测试
*/
public class Account {
//为了封装,将三个属性设置为private
private String name;
private double balance;
private String pwd;
public Account() {
}
public Account(String name, double balance, String pwd) {
this.setName(name);
this.setBalance(balance);
this.setPwd(pwd);
}
//提供两个构造器
public String getName() {
return name;
}
public void setName(String name) {
if (name.length() >= 2 && name.length() <= 4) {
this.name = name;
}else {
System.out.println("你输入的名字不符规则!");
this.name = "无名";
}
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
if (balance>20){
this.balance = balance;
}else {
System.out.println("余额必须大于20,默认取0");
}
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
if (pwd.length()== 6){
this.pwd = pwd;
}else {
System.out.println("密码(必须是六位)默认123456");
this.pwd = "123456";
}
}
//显示账号信息
public void shouInfo() {
Scanner scanner = new Scanner(System.in);
//可以增加权限的校验
System.out.println("请输入密码:");
int key = scanner.nextInt();
if (key == 886699 ){
System.out.println("账号信息 name=" + name + "余额" + balance +"密码" +pwd);
}else{
System.out.println("你无权查看");
}
}
}
AccountTest
package com.hspedu.encap;
public class TestAccount {
public static void main(String[] args) {
//创建Account
Account account = new Account();
account.setName("guo");
account.setBalance(100);
account.setPwd("886699");
account.shouInfo();
}
}
正确运行结果
密码错误时候
不符题意时