我有一个子类“OnlineCourse”。它是“类(class)”的子类。我想在我的类(class)“学生”中返回“在线类(class)”。但我返回的是 null,而不是“EIST”。
这是我所拥有的:
<小时/>public class Student {
public String matriculationNumber;
public String name;
public int age;
public Course study() {
TODO 4:评论下面的代码 将类(class)类型更改为 OnlineCourse 并设置其 “EIST”的标题 返回新类(class)
// Course course = new Course();
// course.join();
// return course;
Course EIST = new OnlineCourse();
EIST.join();
return EIST;
}
}
<小时/>
扩展类(class)的子类,应作为 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();
}
}
最佳答案
我认为您是说类(class)标题显示为空。在这种情况下,您必须对其进行设置才能打印。我还要注意,如果您有 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;
}
关于java - 返回java中的子类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61533274/