【发布时间】:2020-08-15 09:35:05
【问题描述】:
我有一个子类“在线课程”。它是“课程”的子类。我想在我的班级“学生”中返回“在线课程”。但是我得到的不是“EIST”,而是空值。
这是我所拥有的:
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;
}
}
扩展课程的子类,应作为 Student 类中“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();
}
}
【问题讨论】:
-
你的意思是当你打电话给
study()时你得到了null? -
@sc0der 是正确的
-
这是怎么回事?应该返回
OnlineCourse对象 -
你能把完整的代码放上去吗
-
@sc0der 我添加了主方法。真的没有更多了。
标签: java class return subclass