这是主要的课程
**
** Assignment class
**
** This class represents an Assignment.
**
****************************************************/
public class Assignment {
private String name;
private double pointsPossible;
private double pointsEarned;
// Assignment constructor
//
// postcondition: all instance variables are initialized with
// the given values.
public Assignment (String n, double ptsPoss, double ptsEarned) {
name =n;
pointsPossible=ptsPoss;
pointsEarned=ptsEarned;
}
// getName accessor method
//
// postcondition: returns the name of this Assignment public
String getName() {
return name;
}
// getPointsPossible accessor method
//
// postcondition: returns the points possible for this Assignment
public double getPointsPossible() {
return pointsPossible;
}
// getPointsEarned accessor method
//
// postcondition: returns the points earned for this Assignment
public double getPointsEarned() {
return pointsEarned;
}
}
当我尝试在我的子类中使用我的访问器时,我在尝试初始化其变量时遇到错误
这里是子类
import java.util.ArrayList;
/****************************************************
**
** CategoryAssignment class
**
** This class represents an CategoryAssignment.
** Do not add any additional methods to this class.
**
****************************************************/
public class CategoryAssignment extends Assignment {
// declare any new instance variables that you need here
// don't forget to make them private!
// don't declare more that you really need!
// CategoryAssignment constructor
//
// postcondition: all instance variables are initialized with
// the given values.
public CategoryAssignment (String n, double ptsPoss, double ptsEarned, String cat) {
}
// getCategoryName accessor method
//
// postcondition: returns the name of the category associated
// with this CategoryAssignment
public String getCategoryName() {
return cat;
}
}
我无法获取子类的变量来进行初始化。另外,这是一个成绩簿项目,将categories变量存储在数组或ArrayList中是否明智?
答案 0 :(得分:1)
您的子类CategoryAssignment
是否应该调用超类构造函数?类似的东西:
public CategoryAssignment (String n, double ptsPoss, double ptsEarned, String cat) {
super(n, ptsPoss, ptsEarned);
this.cat = cat;
}
您还需要在String cat
中定义CategoryAssignment
属性。
关于你的第二个问题"另外,这是一个成绩簿项目,将categories变量存储在数组或ArrayList中是否明智?",就我在 getter ,cat
变量是一个String。很难判断列表或数组是否最适合您提供的信息。
答案 1 :(得分:0)
在Java中没有隐式构造函数链接这样的东西,即使子类'和超类'构造函数具有相同的签名。您需要将参数显式传递给超类'带有super
关键字的构造函数:
public CategoryAssignment
(String n, double ptsPoss, double ptsEarned, String cat) {
super(n, ptsPoss, ptsEarned, car);
}
答案 2 :(得分:0)
首先: 如果要访问此类,则必须在类中声明变量 cat 。您必须在课程中添加:
private String cat;
下一步: 子类'构造函数中的第一个语句是超类的构造函数。在你的情况下:
public CategoryAssignment(String n, double ptsPoss, double ptsEarned, String cat) {
super(n, ptsPoss, ptsEarned);
this.cat = cat;
}