【问题标题】:The Object Class and Its toString()对象类及其 toString()
【发布时间】:2014-10-23 04:33:12
【问题描述】:

超类 Student 包含: 一个构造函数,它接受与学生就读的学校名称相对应的字符串 一个 toString 方法,它返回 'student at X',其中 X 是学生就读的学校的名称。

为子类 HighSchoolStudent 编写一个类定义,其中包含: 一个接受字符串的构造函数,该字符串用作超类构造函数的参数 一个 toString 方法,它返回“X 的高中生”。此方法必须使用其超类的 toString 方法。

教师注释:您只写子类。 在其中你将有一个构造函数(它有一个参数 - 一个字符串),它将调用超类的构造函数,将这个参数传递给它。 它还将通过返回“high school”以及超类的 toString 方法中返回的内容来覆盖 tostring 方法。

public class HighSchoolStudent extends Student
{
    public String HighSchoolStudent()
    {
        return "high school student at "+super.toString();
    }
}
HighSchoolStudent.java:1: error: constructor Student in class Student cannot be applied to given types;
public class HighSchoolStudent extends Student
       ^
  required: String
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error
1 public class HighSchoolStudent extends Student
2 {
3   public String HighSchoolStudent()
4   {
5       return "high school student at "+super.toString();
6   }
7 }

【问题讨论】:

    标签: java inheritance tostring


    【解决方案1】:

    在Java中,与类同名的方法是构造函数, 所以,应该是:

    public HighSchoolStudent(String schoolName) {
        super(schoolName);
    }
    

    toString 方法应该是:

    public String toString() {
        return "high school " + super.toString();
    }
    

    【讨论】:

      【解决方案2】:

      您的错误是因为该类被称为HighSchoolStudent,并且您还尝试将您的方法命名为HighSchoolStudent。这仅允许作为构造函数的名称。对于覆盖toString,您希望:

      public class HighSchoolStudent extends Student
      {
          @Override
          public String toString()
          {
            return "high school student at "+super.toString();
          }
      }
      

      【讨论】:

      • 谢谢!我猜它不想让我使用@Override。
      【解决方案3】:
      public class HighSchoolStudent extends Student
      {
          public HighSchoolStudent(String schoolName)
          { 
              super(schoolName);
          }
          public String toString() 
          {
              return "high school " + super.toString();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-25
        • 2018-10-06
        • 1970-01-01
        • 2011-04-20
        • 1970-01-01
        相关资源
        最近更新 更多