猿问

给定以下类,完成 Student 类的代码,以便在我们运行 Q01 类时打印以下输出

给定以下类,完成 Student 类的代码,以便在我们运行 Q01 类时打印以下输出。提示:学生类是 Person 的子类


这是输出:


部门:CSE,ID:20101001,姓名:Mark Wahlberg


部门:BBA,ID:20101002,姓名:Zeeko Zaki


部门:CSE,编号:20101002,姓名:Zeeko Zaki


public abstract class Person {

  private String name;

  private Person() {

  }

  Person(String name) {

    this.name = name;

  }

  protected String getName() {

    return name;

  }

  protected void setName(String name) {

    this.name = name;

  }

}

public class Q01 {

  public static void main(String[] args) {

    Student s1 = new Student("CSE", 20101001, "Mark Wahlberg");

    Student s2 = new Student("BBA", 20101002, "Zeeko Zaki");

    s1.printDetail();

    s2.printDetail();

    s2.setDepartment("CSE");

    s2.printDetail();

  }

}

我在班级下面创建了一个新班级


public class Student extends Person{

  public String department="";

  public int id;

  public String name;

  public String Public(String name){

    return name;

  }


  public Student(String department,int id,String name){

    this.department=department;

    this.id=id;

    this.name=name;

  }

  public void setDepartment(String department){

    this.department=department;

  }

  public String getDepartment(){

    return department;

  }

  public void printDetail(){

    System.out.println("Department: "+this.department+", ID: "+this.id+", Name: "+name);

  }

我无法编译这段代码。如何解决这个问题呢?我的错误在哪里?


一只名叫tom的猫
浏览 131回答 1
1回答

慕姐4208626

Student 的构造函数需要先调用父类的构造函数。为此,您需要调用“super”并传递正确的参数,在这种情况下,父类(Person)有 2 个构造函数,默认构造函数是私有的,并且只能在 Person 类中访问,因此您必须使用第二个构造函数子类 Student,它采用字符串名称。艾 public Student(String department,int id,String name){    super(name);    this.department=department;    this.id=id;    this.name=name;}
随时随地看视频慕课网APP

相关分类

Java
我要回答