创建一个教师类包含两个成员变量(姓名年龄)成员方法(展示的方法打印姓名年龄)2、创建一个测试类实例化两个对象并进行赋值,调用成员方法3、进行封装写出两个构造方法(无参和有参),getter和setter方法并通过getter和setter方法进行赋值和获取值
时间: 2023-05-16 16:07:05 浏览: 112
好的,下面是我的回答:
1. 创建教师类:
```java
public class Teacher {
private String name;
private int age;
public Teacher() {}
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("姓名:" + name + ",年龄:" + age);
}
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;
}
}
```
2. 创建测试类:
```java
public class TestTeacher {
public static void main(String[] args) {
Teacher t1 = new Teacher();
t1.setName("张三");
t1.setAge(30);
t1.display();
Teacher t2 = new Teacher("李四", 35);
t2.display();
}
}
```
3. 封装:
```java
public class Teacher {
private String name;
private int age;
public Teacher() {}
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("姓名:" + name + ",年龄:" + age);
}
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 < 0 || age > 100) {
System.out.println("年龄不合法!");
return;
}
this.age = age;
}
}
```
阅读全文