9. 编写一个教师类Teacher,要求: (1) 教师类Teacher属性有: Name:String类对象,代表姓名 Age:int型,代表年龄 Sex:boolen型,代表性别(其中:true代表男,false代表女) Phone:long型,代表联系电话
时间: 2024-11-07 07:19:31 浏览: 4
要编写一个名为`Teacher`的Java类,你可以按照以下结构定义:
```java
public class Teacher {
private String name;
private int age;
private boolean sex;
private long phone;
// 构造器
public Teacher(String name, int age, boolean sex, long phone) {
this.name = name;
this.age = age;
this.sex = sex;
this.phone = phone;
}
// getter and setter methods for accessing the properties
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 boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
// Overriding default toString method to provide a string representation of the Teacher object
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
", sex=" + (sex ? "male" : "female") +
", phone=" + phone +
'}';
}
}
```
在这个类中,我们定义了四个私有的实例变量来存储教师的姓名、年龄、性别和电话号码。构造函数用于初始化这些属性。getter和setter方法用于访问和修改这些属性。`toString()`方法被重写,以便于打印教师对象的内容。
阅读全文