首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将类的值与包含该类的接口进行比较?

如何将类的值与包含该类的接口进行比较?
EN

Stack Overflow用户
提问于 2017-02-03 00:42:20
回答 3查看 74关注 0票数 0

这将是视频中的一种方法,其中IMedia接口可以是视频、文章或记录。只有一个视频和文章使用“名称”字段。

代码语言:javascript
复制
// 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“不能工作,因为界面似乎不知道如何解析。

接口只包含方法体。

代码语言:javascript
复制
//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);
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-02-03 00:56:41

IMedia可能没有name字段,子类也有。所以你必须投,但这是一个糟糕的设计。

你可以有一个新的界面

代码语言:javascript
复制
public interface Nameable {
    public String getName();
}

而你的另一个扩展了

代码语言:javascript
复制
public interface IMedia extends Nameable {
    // other stuff
}

您有一个带有名称字段的类

代码语言:javascript
复制
public class Video implements IMedia {
    private String name;
    public String getName() {
        return this.name;
    }

    // Video things
}

一些没有名称的类仍然实现IMedia,只需为getName()返回null。

你的比较方法应该很好

代码语言:javascript
复制
public boolean sameCorporation(IMedia that) {
  // compare strings correctly, avoid nullpointer
  return that != null && Objects.equals(this.name, that.getName()); 
}

此时最好使用抽象类。

代码语言:javascript
复制
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()); 
    }
}
票数 3
EN

Stack Overflow用户

发布于 2017-02-03 00:54:35

可以在接口getName()中添加IMedia方法。

代码语言:javascript
复制
interface IMedia {
  String getName();
  int length();
  String format();
  boolean sameCorporation(IMedia that);
}

然后,您可以通过调用这个新方法进行比较。

代码语言:javascript
复制
public boolean sameCorporation(IMedia that) {
  return this.getName() == that.getName();
}

考虑到只有VideoArticle有一个名称。可以在Recording.getName()方法中返回null。

票数 1
EN

Stack Overflow用户

发布于 2017-02-03 00:56:45

接口没有属性。它们只提供在类中实现的方法声明。因此,在您的示例中,IMedia接口应该声明一个方法getName或类似的东西。

代码语言:javascript
复制
public interface IMedia {
    String getName();
    //...
    //Your other methods
}

你说过只有文章和视频有名字。所以您可以定义另一个interace,它扩展了IMedia

代码语言:javascript
复制
public interface INamedMedia extends IMedia {
    String getName();
}

然后,VideoArticle类可以实现INamedMedia

我看到的第二件事。name可能是一个字符串。您永远不应该将String与==进行比较。使用equals方法代替。

代码语言:javascript
复制
this.getName().equals(that.getName())
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42014925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档