我正在扩展一个类来存储应用程序所需的一些额外字段,但我正在扩展的类没有 setter 方法,只有一个默认构造函数。
http://restfb.com/javadoc/com/restfb/types/Post.html#Post()
我使用的框架要求 getter 与类型中的字段采用正确的命名格式。但是,由于我无法从构造函数或 setter 设置字段,因此我保留了希望存储在新对象中的初始对象的本地副本。
然后,我重写了从初始对象中提取数据的方法,如下所示:
@Override
public String getMessage() {
return initialPost.getMessage();
}
这似乎不是一种好方法,一个令人烦恼的原因是,如果我想使用所有字段,我就必须重写每个方法。
解决此问题的最佳方法是什么?这是否是组合优于继承的用例?
我想我可能尝试在这里将两者结合起来,这似乎不正确!
public class MyPost extends Post{
private String postId;
private Post initialPost;
private PostType type;
private Brand brand;
private Product product;
private List<Photo.Image> postImages;
感谢所有建议。
最佳答案
你确实结合了组合和继承;这是一个相当令人困惑的情况。我会选择继承,因为您正在将具有更具体目的的对象的行为扩展到该对象。
这也解决了您的问题,因为 Post
类中的 public
方法也可用作其子类中的 public
方法(并且作为这样,框架就可以愉快地使用 getMessage()
而无需您重新定义它。
来 self 的评论:
Post
is essentially an immutable object so it is not intended to be constructed by you. You could override the methods fromPost
inMyPost
and add your own getters/setters, but you should reflect whether or not this is an approach you want to take.
如何实现这一点的示例:
class Post {
private String body;
public String getBody() {
return body;
}
}
class MyPost extends Post {
private String body;
public void setBody(String body) {
this.body = body;
}
@Override
public String getBody() {
return body;
}
}
现在,Post
类中的 getBody()
方法被 MyPost
中的自定义方法覆盖。
关于java - 如何在没有 setter 的情况下扩展对象来获取父类(super class)状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23985124/