我想使用此方法返回一个Course对象,但前提是该对象不为null.
public Course getClass1()
{
if(class1 != null)
{
return class1;
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个'缺少返回语句'错误,因为它可能不会返回任何内容,但如果对象为null,我不想返回任何内容,甚至不返回空字符串.我可以将方法更改为void
public void getClass1()
{
if(class1 != null)
{
System.out.println(class1);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我这样做,我无法调用toString中的方法
public String toString()
{
return super.getName() + "\t" + super.getAge() + "\t" + getStudentNumber() +
"\n" + getClass1() + "\n" + getClass2() + "\n" + getClass3();
}
Run Code Online (Sandbox Code Playgroud)
因为不允许使用void类型.