编写一个 Student2 类,代表学生,实现如下需求:
(1)要求有姓名、性别、身高属性,身高属性不能小于等于零,否则报错,
(2)要求有学生的说明方法,方法输出学生的姓名、性别和身高。
(3)具有两个带参数的构造方法,要求第一个构造方法中,设置学生的性别为
取得。
“男”,其他属性的值从参数中取得;第二个构造方法中,所有的属性值都从参数中
(4)最后编写测试类测试,以两种方式完成对 Student2 对象的初始化工作,测试是否符合需求。
public class Student2 {
String name;
String gender;
double height;
public Student2(String name, double height) throws Exception {
this(name, "男", height);
}
public Student2(String name, String gender, double height) throws Exception {
this.name = name;
this.gender = gender;
if (height <= 0) {
throw new Exception("身高不能小于0");
}
this.height = height;
}
@Override
public String toString() {
return name + ", 性别:" + gender + ", 身高:" + height;
}
public static void main(String[] args) throws Exception {
System.out.println(new Student2("zhangsan", 180));
System.out.println(new Student2("lisi", "女", 170));
System.out.println(new Student2("wangwu", 0));
}
}
运行示例:
把Student2类定义出来,再定义测试类,在测试类中创建 Student2 对象,调用相应的方法测试是否正常。