英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论