74 lines
1.9 KiB
Java
74 lines
1.9 KiB
Java
package chapter4.demo49;
|
|
|
|
// 自定义异常类
|
|
class UserException extends Exception {
|
|
public UserException(String message) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
// 用户操作接口
|
|
interface UserOperation {
|
|
void changePassword(String newPassword) throws UserException;
|
|
void showInfo();
|
|
}
|
|
|
|
// 抽象用户类
|
|
abstract class AbstractUser implements UserOperation {
|
|
protected String username; // 用户名
|
|
protected String password; // 密码
|
|
protected String userType; // 用户类型
|
|
|
|
// 构造方法
|
|
public AbstractUser(String username, String password) {
|
|
this.username = username;
|
|
this.password = password;
|
|
}
|
|
|
|
public String getUsername() {
|
|
return username;
|
|
}
|
|
|
|
// 检查密码是否正确
|
|
public boolean checkPassword(String password) {
|
|
return this.password.equals(password);
|
|
}
|
|
|
|
@Override
|
|
public void showInfo() {
|
|
System.out.println("用户名:" + username + ",用户类型:" + userType);
|
|
}
|
|
}
|
|
|
|
// 普通用户类
|
|
class NormalUser extends AbstractUser {
|
|
public NormalUser(String username, String password) {
|
|
super(username, password);
|
|
this.userType = "普通用户";
|
|
}
|
|
|
|
@Override
|
|
public void changePassword(String newPassword) throws UserException {
|
|
if (newPassword.length() < 6) {
|
|
throw new UserException("密码长度不能小于6位");
|
|
}
|
|
this.password = newPassword;
|
|
}
|
|
}
|
|
|
|
// 管理员类
|
|
class AdminUser extends AbstractUser {
|
|
public AdminUser(String username, String password) {
|
|
super(username, password);
|
|
this.userType = "管理员";
|
|
}
|
|
|
|
@Override
|
|
public void changePassword(String newPassword) throws UserException {
|
|
if (newPassword.length() < 8) {
|
|
throw new UserException("管理员密码长度不能小于8位");
|
|
}
|
|
this.password = newPassword;
|
|
}
|
|
}
|