【问题标题】:Given the following classes, complete the code for the Student class so that the following output is printed when we run the Q01 class [duplicate]给定以下类,完成 Student 类的代码,以便在我们运行 Q01 类时打印以下输出 [重复]
【发布时间】:2019-12-24 19:30:33
【问题描述】:

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

这是输出:

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

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

部门:CSE,ID: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);
  }
} 

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

【问题讨论】:

  • "我无法编译这段代码。" - 为什么不呢?
  • 你遇到了什么错误?
  • 从第 5 行开始的 Student 类中似乎有几个错误
  • public String Public(String name){ 错误的命名约定。不要使用 java 关键字来命名您的属性、成员等...我会假设它是 getter,因此您应该将其命名为 public String getName()
  • 提示:要格式化代码块,只需突出显示所有代码块并单击{} 按钮或按ctrl+k。段落不需要任何 html 格式。 ` 代表单行。

标签: java class abstract


【解决方案1】:

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;
}

【讨论】:

  • 希望不言而喻,您还必须删除 enter code here 才能编译
  • 这是由于问题编辑器中的代码格式错误,我建议进行编辑以修复它。
猜你喜欢
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多