在本例中,我想将一所学校的学生添加到arraylist中,并使用另一个类中定义的另一个方法的多态性格式打印数组列表。
import java.util.ArrayList;
class Student{
public static String name;
public static String gender;
public static int age;
//setting default values for the member variables
public Student(){
name = "default name";
gender = "default gender";
age = 0;
}
//constructor of the parameters for the name, gender, and age.
public Student(String name, String gender, int age){
Student.name = name;
Student.gender = gender;
Student.age = age;
}
// Polymorphism to print with a specific format
public static void printInfo(){
System.out.println(name+", "+gender+", "+age+"\n");
}
}
// creating a class for Male students
class Male extends Student{
private static String gender;
public Male(String name, int age){
super(name, gender, age);
Male.gender = "Male";
}
}
// creating a class for Female students
class Female extends Student{
private static String gender;
public Female(String name, int age){
super(name, gender, age);
Female.gender = "Female";
}
}
// create a class for school to collect all the students
class School{
static ArrayList<Student> students;
public static void addStudent(Student a){
ArrayList<Student> students = new ArrayList<Student>();
students.add(a);
}
public void printAllInfo(){
//call the Student.printInfo method from the Student class
}
}
public class SchoolBuilder{
public static void main(String[] args){
School.addStudent(new Male("Sam",13));
School.addStudent(new Male("John",11));
School.addStudent(new Female("Elle",12));
School.addStudent(new Male("Paul",12));
School.addStudent(new Female("Javinia",11));
School.addStudent(new Male("Paperino",12));
//PRint all by calling School.printAllInfo should print the formatted ArrayList
}
}
输出应如下所示:
Sam, Male, 13
John, Male, 11
Elle, Female, 12
Paul, Male, 12
Javinia, Female, 11
Paperino, Male, 12
我是java新手,就是不知道怎么做。看起来很简单。我为gender创建了两个类,因为以后可以很容易地添加一个包含所有男性或女性的csv文件,并将它们添加到分别调用男性和女性类的数据集中。
谢谢你的时间和帮助。
3条答案
按热度按时间lstz6jyr1#
这将是一类男性,同样是女性:
下一个学校不会有任何静态的东西。
最后,主类应创建学校示例,添加学生并打印:
最后,student中的这个方法不应该有\n in string,因为它将再添加一行。
ou6hu8tu2#
通常,我们通过重写
toString()
方法,然后打印。以下是建设性的批评:这里有很多问题。
在这种情况下,您希望避免使用静态上下文,因为静态变量属于一个类。例如,不是每个学生都有相同的名字。
同样,你也不会打电话
Student.function()
,你会打电话吗this.function()
只为那个学生而不是班上的学生。this
是学生的一个例子。你肯定不想这么做
ArrayList<Student> students = new ArrayList<Student>();
在addstudent()方法中。每次添加学生时都会重置学生列表。将其保留在类级声明中,或者最好添加一个构造函数。pdtvr36n3#
您的实现中有一些错误:
这个
Student
对象不应具有static
领域。static
这意味着它们不是指向特定的对象,而是指向类本身。对象是类的特定实现。你定义了一个
Student
类来定义一个学生的长相,即用特定的设置创建一个学生。当你申报班级时,你说一个学生通常有一个名字,性别和年龄。
当你用构造器刺激学生时(
new Student("Sam", "Male", 13)
)您可以定义具体的实现。班级
Male
以及Female
必须改变。延长期限并没有错Student
类将默认值设置为gender
现场。例如,如果Male
类有一个特定的字段(例如favouriteSoccerPlayer
)而一般学生不应该有。在这种情况下Male
类将从父类继承字段(Student
)并添加另一个额外字段:例如,你可以这样做:
您将调用
Male
对象继承自Student
班级。