【问题标题】:Getter inside an interface and inside an abstract class接口内部和抽象类内部的getter
【发布时间】:2020-05-04 18:40:14
【问题描述】:

我有这个接口,我应该在其中声明一些 getter,并在抽象类中实现它们。这就是我目前所拥有的:

abstract class AbstractArticle implements Article {
    final private String name;
    final private double price;
    final private String description;

    AbstractArticle(String name,double price,String description) {
        this.name = name;
        this.price = price;
        this.description = description;
    }
}

现在的想法是,在这个 AbstractArticle 类中,我将调用 getName() 方法并返回名称;我这样做是否正确?谢谢!

【问题讨论】:

  • 是的,getter 只是返回属性,有时会记录一些东西(尽管你不需要它)。但是,getter 通常在非抽象类中实现

标签: java


【解决方案1】:

是的,你做得对,但请注意,你将无法创建这个抽象类的实例。您将需要实现另一个类,该类继承自您定义的抽象类以使用这些功能。抽象类的优点是您将能够创建多个使用这些实现的类。

使用您的实现的实例将声明如下:

class MyCustomArticle extends AbstractArticle {
    // Some other functions and variables
}

【讨论】:

  • 哦,是的,我知道,实际上这就是我现在正在处理的部分,创建另外两个继承抽象类的类。谢谢你的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
  • 1970-01-01
  • 2015-08-01
  • 2011-12-03
  • 1970-01-01
相关资源
最近更新 更多