Search code examples
javaclassoverridingextend

Java Extending Java Classes and Overriding Their Methods


I am to create a Java console application that defines a class, extends it into two other classes, overrides the toString() for all three classes, instantiates the classes into three objects, invokes the toString() on these objects, and prints out the return value of each toString() invocation.

The application will instantiates three objects from the Course, FlexPathCourse, and GuidedPathCourse and invokes their corresponding toString() methods.

I have the codes below. But for the FlexPathCourse.java and GuidedPathCourse.java, I am getting an error message "Constructor object in class object cannot be applied to given types" at where "super(code1, hours, title1)" is. Can you explain what that means and what I should do instead? Thank you in advance.

Main Class

public class U1A1_InheritOverridetoString {

    public static void main(String[] args) {
        Course c1 = new Course("TBD", 3, "TBD");
        FlexPathCourse c2 = new FlexPathCourse("IT2230", 3, "Introduction to Database Systems");
        GuidedPathCourse c3 = new GuidedPathCourse("ITFP4739", 3, "Mobile Cloud Computing Application Development");

        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);
    }

}

Course.java

public class Course {
    protected String code;
    protected int creditHours;
    protected String title;

    public Course(String code1, int hours, String title1){
            code = code1;
            creditHours = hours;
            title = title1;
    }

    @Override
    public String toString(){
        return "Java class name = 'Course' " + "Course Code = " + code;
    }
}

FlexPathCourse.java

public class FlexPathCourse {
    private String optionalResources;

    public FlexPathCourse (String code1, int hours, String title1){
        super(code1, hours, title1);
    }
        @Override
        public String toString(){
            return "Java class name = 'FlexPathCourse' " + "Course Code = " + code;
        }

    }

GuidedPathCourse.java

public class GuidedPathCourse {
    private String requiredResources;
    private int duration;

    public GuidedPathCourse(String code1, int hours, String title1){
        super(code1, hours, title1);
    }
    @Override
    public String toString(){
        return "Java class name = 'GuidedPathCourse' " + "Course Code = " + code;
    }
}

Solution

  • in your GuidedPathCourse and FlexPathCourse add extends Course like so:

    public class GuidedPathCourse extends Course {