我不明白为什么这个程序不起作用。多态性

时间:2017-03-14 11:11:13

标签: java inheritance arraylist polymorphism override

我最近开始编程,我忙于继承,多态和覆盖。现在我刚刚制作了这个程序,由于某些原因它不起作用。 编译器强调" =新的Arraylist();但我不知道为什么。

代码如下:

超级课程:人

public class Person {
private String firstName;
private String lastName;

public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

public void print() {
    System.out.println("\t" + firstName + " " + lastName);
}
}

子类:老师

public class Teacher extends Person {
public Teacher(String firstName, String lastName) {
    super(firstName, lastName);
}

public void print() {
    System.out.println("Professor Details: ");
    super.print();
}

}

子类学生:

public class Student extends Person {
private int graduationYear;
private double gpa;

public Student(String firstName, String lastName, int graduationYear, double gpa) {
    super(firstName, lastName);
    this.graduationYear = graduationYear;
    this.gpa = gpa;
}

public void print() {
    System.out.println("Student Details: ");
    super.print();
    System.out.println("\t" + graduationYear);
    System.out.println("\t" + gpa);
}
}

主要类:(在我初始化arraylist时,由于某种原因它不起作用。(Fat是编译器中的错误:Arraylist persons = new Arraylist ();

public class Main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    ArrayList<Person> persons = new Arraylist();
    persons.add(new Student("Sam", "Young", 2017, 3.6));
    persons.add(new Student("Dan", "Sella", 2012, 2.5));
    persons.add(new Student("Kevin", "Cane", 2016, 2.7));

    for(Person person : persons) {
        person.print();
    }
}

}

感谢任何帮助。

3 个答案:

答案 0 :(得分:5)

ArrayList初始化如下:

ArrayList<Person> persons = new ArrayList<>();

或者,如果您使用的是Java SE 7以下的版本:

ArrayList<Person> persons = new ArrayList<Person>();

注意<>(Diamond)和ArrayList。

答案 1 :(得分:0)

您应该创建ArrayList对象,如下面的代码:

ArrayList<Person> persons = new ArrayList<Person>();

在上面你遗漏了在对象创建中添加<Person>

答案 2 :(得分:0)

您的代码:

ArrayList<Person> persons = new Arraylist();

ArrayList persons = new Arraylist (); 您的案例错误

ArrayList<Person> persons = new ArrayList<Person>();

如果您仍然有错误,可能会将您的java编译器级别升级到1.5或更高