这将是视频中的一种方法,其中IMedia接口可以是视频、文章或记录。只有一个视频和文章使用“名称”字段。
// is the name of this Video the same
// as that of the given IMedia?
public boolean sameCorporation(IMedia that) {
return (this.name == that.name);
}我知道"this.name == that.name“不能工作,因为界面似乎不知道如何解析。
接口只包含方法体。
//to represent different types of news media
interface IMedia {
// compute the length of this IMedia
int length();
// formats the title, corporation, and episode number of IMedia
String format();
// is the corporation of this media the same
// as the corporation of the given media?
boolean sameCorporation(IMedia that);
}发布于 2017-02-03 00:56:41
IMedia可能没有name字段,子类也有。所以你必须投,但这是一个糟糕的设计。
你可以有一个新的界面
public interface Nameable {
public String getName();
}
而你的另一个扩展了
public interface IMedia extends Nameable {
// other stuff
}
您有一个带有名称字段的类
public class Video implements IMedia {
private String name;
public String getName() {
return this.name;
}
// Video things
}
一些没有名称的类仍然实现IMedia,只需为getName()返回null。
你的比较方法应该很好
public boolean sameCorporation(IMedia that) {
// compare strings correctly, avoid nullpointer
return that != null && Objects.equals(this.name, that.getName());
}此时最好使用抽象类。
public interface IMedia extends Nameable {
// other stuff
boolean sameCorporation(IMedia that);
}
public abstract class AbstractMedia implements IMedia {
public abstract String getName();
public boolean sameCorporation(IMedia that) {
return that != null && Objects.equals(this.getName(), that.getName());
}
}发布于 2017-02-03 00:54:35
可以在接口getName()中添加IMedia方法。
interface IMedia {
String getName();
int length();
String format();
boolean sameCorporation(IMedia that);
}然后,您可以通过调用这个新方法进行比较。
public boolean sameCorporation(IMedia that) {
return this.getName() == that.getName();
}考虑到只有Video和Article有一个名称。可以在Recording.getName()方法中返回null。
发布于 2017-02-03 00:56:45
接口没有属性。它们只提供在类中实现的方法声明。因此,在您的示例中,IMedia接口应该声明一个方法getName或类似的东西。
public interface IMedia {
String getName();
//...
//Your other methods
}你说过只有文章和视频有名字。所以您可以定义另一个interace,它扩展了IMedia。
public interface INamedMedia extends IMedia {
String getName();
}然后,Video和Article类可以实现INamedMedia。
我看到的第二件事。name可能是一个字符串。您永远不应该将String与==进行比较。使用equals方法代替。
this.getName().equals(that.getName())https://stackoverflow.com/questions/42014925
复制相似问题