与扩展和字段混淆

7gs2gvoe  于 2021-07-08  发布在  Java
关注(0)|答案(3)|浏览(232)

基本上,我打算将gettimestamp访问器方法和timestamp字段从messagepost移到post,但是当我这样做时,会出现“has private access in”错误。我怎样才能解决这个问题?我知道我可以保护字段,但我不认为这是一个好的做法,我尝试使用getter和setter,但我得到了一个意想不到的类型错误。

public class MessagePost extends Post
{
    private String username;  // username of the post's author
    private String message;   // an arbitrarily long, multi-line message

    private int likes;
    private ArrayList<String> comments;

    public MessagePost(String author, String text)
    {
        username = author;
        message = text;
        timestamp = System.currentTimeMillis(); //where im getting the errors
        likes = 0;
        comments = new ArrayList<>();
    }
public class Post
{
    private long timestamp;

    public Post(){
        this.timestamp=timestamp;

    }
    public long getTimeStamp()
    {
        return this.timestamp;
    }

}
xlpyo6sf

xlpyo6sf1#

private 成员在定义它们的类之外是不可访问的。要从继承类访问成员,您需要查找 protected 访问修饰符:

protected long timestamp;

或者让成员保持私有并设置受保护的setter:

private long timestamp;

protected void setTimeStamp (long time) {
    this.timestamp = time;
}

旁注。。。这看起来像个bug:

public Post(){
    this.timestamp=timestamp;
}

它把这个领域设置为自己。也许您想在该构造函数中包含一个参数:

public Post(long timestamp){
    this.timestamp=timestamp;
}

在这种情况下,您可能不需要任何setter或 protected 所有成员,作为 MessagePost 构造函数需要传递 timestamp 对客户的价值 Post 建造师。也许是这样的:

public MessagePost(String author, String text)
{
    super(System.currentTimeMillis());
    username = author;
    message = text;
    likes = 0;
    comments = new ArrayList<>();
}
sdnqo3pr

sdnqo3pr2#

这个 MessagePost 构造函数不应该初始化时间戳。因为它属于 Post ,其构造函数负责初始化:

// In the Post class
public Post() {
    this.timestamp = System.currentTimeMillis();
}

// In the MessagePost class
public MessagePost(String author, String text) {
    // Post() is implicitly called here, and timestamp is initiazlied
    username = author;
    message = text;
    likes = 0;
    comments = new ArrayList<>();
}
owfi6suc

owfi6suc3#

移动这条线:

timestamp = System.currentTimeMillis(); //where im getting the errors

从messagepost的构造函数到post的构造函数,替换不太合理的行(根据@david的侧注)。你必须初始化 timestamp 毕竟有些事。有什么比最初设置为当前时间更有意义的呢。
如果你想设置 timestamp 对于其他内容,在post类中添加setter。

相关问题