有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

遇到上述问题:我想显示学生的信息。我创造了家长班的人,并继承给班上的学生

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以输入,但在子类中重写getName以显示各自的名称


共 (1) 个答案

  1. # 1 楼答案

    你的错误:

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

      ListStudent=新建ListStudent()
      大学生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();
        }   
    }