题目描述
使用封装编写Person类。要求:类具有姓名、年龄、体重;其中,如年龄小于等于0岁,则输出“年龄出错,使用默认18岁代替”;如体重小于等于0,则输出“体重出错,使用默认100斤代替”;
编写方法talk(),输出“我是:XX,今年:XX岁”;为各属性设置赋值和取值方法;在控制台输出相关信息
案例代码
public class Person {
private String name;
private int age;
private double weight;
public Person(String name, int age, double weight) {
setName(name);
setAge(age);
setWeight(weight);
}
public void talk() {
System.out.println("我是:" + name + ",今年:" + age + "岁");
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
if (age <= 0) {
System.out.println("年龄出错,使用默认18岁代替");
this.age = 18;
} else {
this.age = age;
}
}
public void setWeight(double weight) {
if (weight <= 0) {
System.out.println("体重出错,使用默认100斤代替");
this.weight = 100;
} else {
this.weight = weight;
}
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
public static void main(String[] args) {
Person person = new Person("张三", -5, 70);
person.talk();
System.out.println("姓名:" + person.getName());
System.out.println("年龄:" + person.getAge());
System.out.println("体重:" + person.getWeight());
}
}
© 版权声明
本站资源来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!
THE END