我正在尝试为类HthsStudent创建一个构造函数,它从类Student继承变量和状态。 (学生从类Person继承变量和状态。)
问题是,java不喜欢我尝试这样做的方式,并且一直告诉我,我正在做的事情是错的,尽管这正是我在课堂上做的那样。它告诉我有一个“无效的方法声明,需要返回类型”错误,但我没有找到解决方法。
我做错了什么,我该如何解决?
谢谢!
/**
* Write a description of class Persn here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Person
{
String firstName;
String lastName;
public Person (String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString ()
{
return lastName + ", " + firstName;
}
}
/**
* Write a description of class Student here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Student extends Person
{
int gradeLevel;
private static int studentId = 0;
public Student (String firstName, String lastName, int gradeLevel)
{
super(firstName, lastName);
this.gradeLevel = gradeLevel;
if (gradeLevel > 5 || gradeLevel < 0)
{
gradeLevel = 0;
}
studentId = studentId + 1;
}
public int getLevel()
{
return gradeLevel;
}
public String toString ()
{
return lastName + ", " + firstName + "\nGrade Level: " + gradeLevel + "\nID #: " + studentId;
}
}
/**
* Write a description of class HTHSStudent here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class HTHSStudent extends Student
{
double gpa;
public HthsStudent (String firstName, String lastName, int gradeLevel, double gpa)
{
super(firstName, LastName, gradeLevel);
this.gpa = gpa;
if (gpa > 5.0 || gpa < 1.0)
{
gpa = 0.0;
}
}
public String toString()
{
return lastName + ", " + firstName + "\nGrade Level: " + gradeLevel + "\nID #: " + studentId + "\nGPA: " + gpa;
}
}
答案 0 :(得分:1)
您没有正确地使用最后一堂课。你有:
class HTHSStudent extends Student
{
double gpa;
public HthsStudent (String firstName, String lastName, int gradeLevel, double gpa)
应该是
class HTHSStudent extends Student
{
double gpa;
public HTHSStudent (String firstName, String lastName, int gradeLevel, double gpa)
甚至更好:
class HthsStudent extends Student {
private double gpa;
public HthsStudent (String firstName, String lastName, int gradeLevel, double gpa)
请注意,对于Java标识符,大写很重要
同样如我的评论中所述,您还有另一个不相关的问题,即您的studentId字段绝对应该不是静态的。此字段对于每个 Student对象必须是唯一的,如果您将其设置为静态,它将成为该类的属性,因此对所有学生都是相同的。如果您将其设置为静态以修复编译器错误,那么您修复了错误的错误。正确的解决方法是不要尝试以静态方式引用它,不在课堂上。