Search code examples
javainheritanceconstructorsubclasssuperclass

Constructor of subclass


Here's the main class

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

and when I attempt to use my accessors in my subclass i get an error while trying to initialize its variables

here's the subclass

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

I can't get the variables of the subclass to initialize. Also with this being a grade book project would it be smart to store the categories variable in an array or an ArrayList?


Solution

  • Shouldn't your subclass CategoryAssignment call the super class constructor? Something like:

    public CategoryAssignment (String n, double ptsPoss, double ptsEarned, String cat) {
        super(n, ptsPoss, ptsEarned);
        this.cat = cat;
    }
    

    You will also need to define the String cat attribute in CategoryAssignment.

    Regarding your second question "Also with this being a grade book project would it be smart to store the categories variable in an array or an ArrayList?", as far as I can see in the getter, the cat variable is a String. Hard to tell whether a list or an array would be most suitable with the information you provide.