【问题标题】:return a subclass-type in java在java中返回一个子类类型
【发布时间】: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


【解决方案1】:

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

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

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

在 Course 中,您需要一个 setter 方法作为标题,例如 -

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

在学生中

public Course study(String courseTitle) {
    Course EISTCourse = new OnlineCourse();
    EISTCourse.setCourseTitle(courseTitle);
    EISTCourse.join();
    return EISTCourse;
}

【讨论】:

  • 由于标题是公开的,他不需要 setter 方法。在这种情况下,他应该编写适当的构造函数,而不是使用空默认构造函数。
猜你喜欢
  • 2022-10-14
  • 2019-03-12
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 2010-10-18
  • 1970-01-01
  • 2018-11-27
  • 2013-10-17
相关资源
最近更新 更多