线程“main”java.lang中的异常。 NoSuchMethodException

时间:2016-08-15 11:20:28

标签: java inheritance arraylist

遇到了上述问题:我想显示学生的信息。我创建了父类People并继承到了Student类。

public class ListPeople {
protected String name;

List<ListPeople> listPeople = new ArrayList<ListPeople>();

 public void setName() {

     Scanner input = new Scanner(System.in);
     for (int i = 1; i < 2; i++) {

         ListPeople people = new ListPeople();   //object of parent class

         System.out.print("Enter your Name: ");
         people.name = input.nextLine();

         listPeople.add(people);
     }
 }

 public class ListStudent extends ListPeople {
 public void getName() {
    for (ListPeople people : listPeople) {
        System.out.print("Name of Student:");
        System.out.print(people.name);

    }
  }
 }
  public class ListMain {
 public static void main(String[] args) {
    ListPeople people = new ListStudent();
    people.setName();

    ListStudent student = new ListStudent();
    student.getName();
}
}

我必须创建两种对象学生和教师。我继承方法setName来输入,但覆盖子clas中的getName以显示相应的名称。

1 个答案:

答案 0 :(得分:0)

你的错误:

  • 您无法在java
  • 中的文件中定义多个公共类
  • 这将创建ListStudent类型的新实例,这意味着您的listPeople最初为空。

    ListStudent student = new ListStudent();
       student.getName();

//很少修改

import java.util.*;

class ListPeople {
    protected String name;

    protected List<ListPeople> listPeople = new ArrayList<ListPeople>();

    public void setName() {

        Scanner input = new Scanner(System.in);
        for (int i = 1; i < 2; i++) {

            ListPeople people = new ListPeople();   //object of parent class

            System.out.print("Enter your Name: ");
            people.name = input.nextLine();

            listPeople.add(people);
        }   

    }   

    public void getName(){

    }   

}

class ListStudent extends ListPeople {
    public void getName() {
        for (ListPeople people : listPeople) {
        System.out.print("Name of Student:");
        System.out.println(people.name);

        }   
    }   
}


public class ListMain {
    public static void main(String[] args) {
        ListPeople people = new ListStudent();
        people.setName();
        people.getName();
    }   
}