3.编写Teacher01类,要求如下: (1)2个属性:所在学校(school)、姓名(name) (2)封装所有属性,且所有属性可读可写 (3)编写测试类TestTeacher01,展示封装后各属性的读写方法的使用 4.编写Teacher02类,要求如下: (1)2个属性:所在学校(school)、姓名(name)、年龄(age) (2)封装所有属性,且学校为只写属性,年龄只能接收18-30之间的值 (3)编写测试类TestTeacher02,展示封装后各属性的读写方法的使用 5.编写Teacher03类,要求如下: (1)2个属性:所在学校(school)、姓名(name)、年龄(age) (2)封装所有属性,且学校为只读属性,年龄只能接收18-30之间的值 (3)编写测试类TestTeacher03,展示封装后各属性的读写方法的使用
时间: 2024-03-12 19:43:41 浏览: 14
3. 实现Teacher01类:
```java
public class Teacher01 {
private String school;
private String name;
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
测试类TestTeacher01:
```java
public class TestTeacher01 {
public static void main(String[] args) {
Teacher01 teacher = new Teacher01();
teacher.setName("张三");
teacher.setSchool("清华大学");
System.out.println("姓名:" + teacher.getName());
System.out.println("学校:" + teacher.getSchool());
}
}
```
4. 实现Teacher02类:
```java
public class Teacher02 {
private String school;
private String name;
private int age;
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 18 && age <= 30) {
this.age = age;
} else {
System.out.println("年龄必须在18岁到30岁之间!");
}
}
}
```
测试类TestTeacher02:
```java
public class TestTeacher02 {
public static void main(String[] args) {
Teacher02 teacher = new Teacher02();
teacher.setName("李四");
teacher.setSchool("北京大学");
teacher.setAge(20);
System.out.println("姓名:" + teacher.getName());
System.out.println("学校:" + teacher.getSchool());
System.out.println("年龄:" + teacher.getAge());
}
}
```
5. 实现Teacher03类:
```java
public class Teacher03 {
private final String school;
private String name;
private int age;
public Teacher03(String school) {
this.school = school;
}
public String getSchool() {
return school;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 18 && age <= 30) {
this.age = age;
} else {
System.out.println("年龄必须在18岁到30岁之间!");
}
}
}
```
测试类TestTeacher03:
```java
public class TestTeacher03 {
public static void main(String[] args) {
Teacher03 teacher = new Teacher03("上海交通大学");
teacher.setName("王五");
teacher.setAge(25);
System.out.println("姓名:" + teacher.getName());
System.out.println("学校:" + teacher.getSchool());
System.out.println("年龄:" + teacher.getAge());
}
}
```
阅读全文