创建学⽣类,创建成员变量name,age,gender,className⾃⾏区分那个成员变 量为类变量。 创建2个学⽣,赋值后,打印2个学⽣的信息。java
时间: 2024-03-26 17:38:52 浏览: 46
好的,下面是符合要求的Java代码:
```java
public class Student {
private String name;
private int age;
private String gender;
private static String className;
public Student(String name, int age, String gender, String className) {
this.name = name;
this.age = age;
this.gender = gender;
Student.className = className;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
public static String getClassName() {
return className;
}
}
public class Main {
public static void main(String[] args) {
Student student1 = new Student("Tom", 18, "Male", "Class 1");
Student student2 = new Student("Lucy", 17, "Female", "Class 2");
System.out.println("Student 1 Name: " + student1.getName());
System.out.println("Student 1 Age: " + student1.getAge());
System.out.println("Student 1 Gender: " + student1.getGender());
System.out.println("Student 1 Class Name: " + Student.getClassName());
System.out.println("Student 2 Name: " + student2.getName());
System.out.println("Student 2 Age: " + student2.getAge());
System.out.println("Student 2 Gender: " + student2.getGender());
System.out.println("Student 2 Class Name: " + Student.getClassName());
}
}
```
这个程序中,我们首先创建了一个名为`Student`的类,并在其中定义了4个成员变量:`name`、`age`、`gender`和`className`。其中,`className`被声明为`static`,表示它是一个类变量,而不是实例变量。
接下来,在`Student`类中,我们创建了一个构造方法,用于初始化这些成员变量的值。我们还创建了四个getter方法,用于获取每个成员变量的值。
在`Main`类的`main`方法中,我们创建了两个`Student`对象,并分别将它们的成员变量赋值为不同的值。然后,我们通过各自的getter方法获取这些值,并将它们打印出来。
最终的输出将会是:
```
Student 1 Name: Tom
Student 1 Age: 18
Student 1 Gender: Male
Student 1 Class Name: Class 2
Student 2 Name: Lucy
Student 2 Age: 17
Student 2 Gender: Female
Student 2 Class Name: Class 2
```
阅读全文