在现实中,人的年龄和体重都不能小于0;更恐怖的是如果忘记给名字赋值就会成为无名氏。要求使用封装完成对属性的控制,当年龄输出错误时提示出错,默认为18;当姓名输入“上帝”时,报错,默认是无名氏
对name和age属性进行如下封装。
public class Person {
private String name;
private Integer age;
public String getName() {
return null == name ? "无名氏" : name;
}
public void setName(String name) {
if ("上帝".equals(name)) {
throw new IllegalArgumentException();
}
this.name = name;
}
public Integer getAge() {
return null == age ? 18 : age;
}
public void setAge(Integer age) {
if (age < 0) {
throw new IllegalArgumentException();
}
this.age = age;
}
}
如果你是对面向对象的概念不清晰的话,可以看看我这个示例:
import java.util.Scanner;
import java.util.StringJoiner;
/**
* @description
* 要求使用封装完成对属性的控制
* 当年龄输出错误时提示出错
* @date 2022/10/31 19:00:50
*/
public class PersonTest {
public static void main(String[] args) {
// 创建输入扫描仪
Scanner in = new Scanner(System.in);
Person person = new Person();
// 从控制台中读取输入
System.out.println("请输入姓名:");
person.setName(in.next());
System.out.println("请输入年龄");
person.setAge(in.nextInt());
System.out.println("请输入体重");
person.setWeight(in.nextDouble());
// 打印人类信息
System.out.println(person);
}
/**
* 人类
*/
static class Person {
/** 姓名 */
private String name = "无名氏";
/** 年龄 */
private Integer age;
/** 体重 */
private Double weight;
public Person() {
}
public Person(String name, Integer age, Double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
if("上帝".equals(name)) {
throw new RuntimeException("上帝不是一个有效的姓名");
} else {
this.name = name;
}
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
if(age < 0) {
throw new RuntimeException("年龄不能小于0");
} else {
this.age = age;
}
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
if(weight < 0) {
throw new RuntimeException("体重不能小于0");
} else {
this.weight = weight;
}
}
@Override
public String toString() {
return new StringJoiner(", ", Person.class.getSimpleName() + "[", "]")
.add("name='" + name + "'")
.add("age=" + age)
.add("weight=" + weight)
.toString();
}
}
}