返回java中的子类类型

问题描述 投票:0回答:1

我有一个子类“ OnlineCourse”。它是“课程”的子类。我想在班级“学生”中返回“在线课程”。但是我没有返回“ EIST”,而是返回null。

这里是我所拥有的:


public class Student {

public String matriculationNumber;
public String name;
public int age;

public Course study() {

TODO 4:注释下面的代码将课程类型更改为OnlineCourse并设置其“ EIST”的标题返回新课程

    // Course course = new Course();
    // course.join();
    // return course;

    Course EIST = new OnlineCourse(); 
    EIST.join();
    return EIST;
}
}

扩展课程的子类,应作为学生类中“ EIST”的返回类型启动。

public class OnlineCourse extends Course{
public URL livestreamUrl; 
public Course join() {
    System.out.println("joined the course " + title);
    return this; 
}
public Course drop() {
    System.out.println("dropped out of the course" + title);
    return this; 
 }
}

public abstract class Course {

public String title;
public String description;
public LocalDate examDate;
public List<Lecture> lectures;

public abstract Course join();
public abstract Course drop();
}

主要方法:

public class Main {

public static void main(String[] args) {
    var student = new Student();
    student.matriculationNumber = "01234567";
    student.name = "Joe Doe";
    student.age = 42;
    student.study();
 }
}
java class return subclass
1个回答
0
投票

[我想您是说课程标题显示为空。在这种情况下,您必须对其进行设置以进行打印。我还要注意的是,您拥有EIST的地方-只是一个变量名,它可以是任何东西,并且对任何值都没有影响。

如果我猜的话,我想你想要这样的东西-

public static void main(String[] args) {
    var student = new Student();
    student.matriculationNumber = "01234567";
    student.name = "Joe Doe";
    student.age = 42;
    student.study("EIST");
 }

当然,在课程中,您希望使用setter方法,例如-

public setCourseTitle(String title) {
    this.title = title;
}

在学生中

public Course study(String courseTitle) {
    Course EISTCourse = new OnlineCourse();
    EISTCourse.setCourseTitle(courseTitle);
    EISTCourse.join();
    return EISTCourse;
}
© www.soinside.com 2019 - 2024. All rights reserved.