编写学生类Student,属性包含姓名,年龄,性别,根据该类分别创建五个学生对象,如下:
public class Student {
private String name;
private int age;
private String sex;
public Student(String name,int age,String sex){
this.name=name;
this.age=age;
this.sex=sex;
}
public static void main(String[] args){
//定义学生对象,直接在构造函数里给值,也可以用set设置值,get获取值
Student st1=new Student("xiaobai",12,"男");
Student st2=new Student("xiaohong",12,"女");
Student st3=new Student("xiaoyi",12,"女");
Student st4=new Student("xiaoer",12,"男");
Student st5=new Student("xiaodong",12,"女");
System.out.println("学生一:"+st1);
System.out.println("学生二:"+st2);
System.out.println("学生三:"+st3);
System.out.println("学生四:"+st4);
System.out.println("学生五:"+st5);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
结果:
学生一:Student [name=xiaobai, age=12, sex=男]
学生二:Student [name=xiaohong, age=12, sex=女]
学生三:Student [name=xiaoyi, age=12, sex=女]
学生四:Student [name=xiaoer, age=12, sex=男]
学生五:Student [name=xiaodong, age=12, sex=女]