写一个人类,有成员用java写属性:姓名、年龄、性别,有两个成员方法
时间: 2024-05-19 07:13:28 浏览: 133
public class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public void introduce() {
System.out.println("My name is " + name + ", I am " + age + " years old, and I am " + gender + ".");
}
public void haveBirthday() {
age++;
System.out.println("Happy birthday to me! I am now " + age + " years old.");
}
}
相关问题
java Person包含3个成员属性:姓名、性别和年龄
Java code:
public class Person {
private String name;
private String gender;
private int age;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
java写一个学生类包含属性有学号性别姓名年龄 实现操作增加一个学生
下面是一个Java实现的学生类,包含属性:学号、性别、姓名、年龄,以及实现的操作:增加一个学生。
```java
public class Student {
private String id; // 学号
private String gender; // 性别
private String name; // 姓名
private int age; // 年龄
// 构造方法
public Student(String id, String gender, String name, int age) {
this.id = id;
this.gender = gender;
this.name = name;
this.age = age;
}
// getter和setter方法
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
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 static void addStudent(List<Student> students, Student student) {
students.add(student);
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
// 增加一个学生
Student student = new Student("001", "男", "张三", 20);
Student.addStudent(students, student);
// 输出学生列表
for (Student s : students) {
System.out.println(s.getId() + " " + s.getGender() + " " + s.getName() + " " + s.getAge());
}
}
}
```
阅读全文