在接口内部和抽象类内部的获取器 (Getter)

huangapple go评论81阅读模式
英文:

Getter inside an interface and inside an abstract class

问题

我有一个接口,在这个接口中,我应该声明一些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()方法并返回name;这样做的方式是否正确?谢谢!

英文:

I have this interface in which i am supposed to declare some getters, and implement those in an abstract class. And this is what I have so far:

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;
	}
}

Now the idea is that inside this AbstractArticle class I will call the getName() method an just return name; Am I doing this the right way or not? Thanks !

答案1

得分: 1

是的,你做得对,但要注意你将无法创建此抽象类的实例。你需要实现另一个继承自你所定义的抽象类的类来使用那些函数。抽象类的优势在于你可以创建多个使用这些实现的类。

使用你的实现创建的实例将会如下声明:

class MyCustomArticle extends AbstractArticle {
    // 其他一些函数和变量
}
英文:

Yes, you are doing it correctly but note that you will not be able to create instance of this abstract class. You will need to implement another class that inherits from the abstract class you defined to use those function. The advantage of abstract classes is that you will be able to create several classes that uses those implementations.

The instance using your implementation will be declared as follow :

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

huangapple
  • 本文由 发表于 2020年5月5日 02:40:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/61599314.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定