1
编写一个Student1 类,代表学生,要求如下
具有属性:姓名,年龄,其中年龄不能小于16岁,否则输出错误信息
具有方法:自我介绍,负责输出该学生的姓名,年龄。
编写测试类StudentTest 进行测试,看是否符合要求
提示:
在学生类中的SetAge()方法中验证年龄的大小
在测试类总分别测试学员的年龄小于16岁,大于16时的输出结果.
public class Student1{ //1.成员变量 private String name; private int age; //2.构造器 //3.成员方法 public void intruction(){ System.out.println("我叫" + this.name + ",年龄" + this.age); } public void setName(String nema){ this.name = name; } public String getName(){ return this.name; } public void setAge(int age){ if(age < 16){ System.out.println("年龄太小。"); } this.age = age; } public int getAge(){ return this.age; } }
public class StudentTest{
public static void main(String[] args){
Student1 stu = new Student1();
stu.setName("张三");
stu.setAge(12);
stu.intruction();
}
}
2:编写一个类 Student2.代表学生,要求如下
具有属性:姓名,年龄,性别和专业。
具有方法:自我介绍,负责输出该学生的姓名,年龄,性别和专业。
具有两个带参的构造方法:
第一个构造方法中,设置学员的性别为男,专业为计算机,终于属性的值由参数给定,
第二个构造方法中,所有属性的值都由参数给定。
编写测试类StudentTest2类 进行测试,分别以两种方式完成对两个Student2 对象的初始化工作
并分别调用他们的自我介绍方法,看看输出的结果是否正确。
public class Student2{
//成员变量:姓名,年龄,性别和专业
private String name;
private int age;
private String sex;
private String subject;
//构造器
public Student2(String name, int age){
this.name = name;
this.age = age;
this.sex = "男";
this.subject = "计算机";
}
public Student2(String name, int age, String sex, String subject){
this.name = name;
this.age = age;
this.sex = sex;
this.subject = subject;
}
//成员方法
public void intruction(){
System.out.printf("姓名:%s,年龄:%d,性别:%s,职业:%s",this.name,this.age,this.sex,this.subject);
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String getSex(){
return this.sex;
}
public String getSubject(){
return this.subject;
}
}
public class StudentTest2{
public static void main(String[] args){
Student2 stu01 = new Student2("aaa",11);
stu01.intruction();
System.out.println();
Student2 stu02 = new Student2("bbb",22,"女","软件");
stu02.intruction();
}
}