根据UML写出对应的代码,为给定的类编写相应的无参数的构造方法和带参数的构造方法,以及修改和访问每个属性的方法,并在main方法中进行实例化。 ————————— | Student | |————————| |-name:String | |-age:int | |-sex: char | ————————
时间: 2023-07-31 19:09:40 浏览: 157
以下是对应的代码:
```
public class Student {
private String name;
private int age;
private char sex;
public Student() {}
public Student(String name, int age, char sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(char sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public char getSex() {
return sex;
}
public static void main(String[] args) {
Student student1 = new Student();
Student student2 = new Student("John", 18, 'M');
System.out.println("Student 1: " + student1.getName() + ", " + student1.getAge() + ", " + student1.getSex());
System.out.println("Student 2: " + student2.getName() + ", " + student2.getAge() + ", " + student2.getSex());
student1.setName("Jane");
student1.setAge(20);
student1.setSex('F');
System.out.println("Student 1 after modification: " + student1.getName() + ", " + student1.getAge() + ", " + student1.getSex());
}
}
```
在main方法中,我们实例化了两个学生对象,一个使用无参数构造方法,另一个使用带参数构造方法。然后,我们通过修改和访问每个属性的方法来修改学生对象的属性,并在控制台上打印出学生对象的属性值。
阅读全文