简体   繁体   English

如何从子类访问私有成员

[英]How do I access a private member from a subclass

Trying to print the username in the method printShortSummary in the MessagePost class. 尝试在MessagePost类的printShortSummary方法中打印用户名。 The username is private in the Post class. 用户名在Post类中是私有的。 Doing this for educational purposes. 这样做是出于教育目的。 Still getting error that the username is private in Post. 仍然收到用户名在Post中为私人用户的错误。

import java.util.ArrayList;

/**
 * This class stores information about a news feed post in a 
 * social network. Posts can be stored and displayed. This class
 * serves as a superclass for more specific post types.
 * 
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class Post 
{
    private String username;  // username of the post's author
    private long timestamp;
    private int likes;
    private ArrayList<String> comments;

    /**
     * Constructor for objects of class Post.
     * 
     * @param author    The username of the author of this post.
     */
    public Post(String author)
    {
        username = author;
        timestamp = System.currentTimeMillis();
        likes = 0;
        comments = new ArrayList<>();
    }

    public void getUserName()
    {

      getUserName();

    }
    /**
     * Record one more 'Like' indication from a user.
     */
    public void like()
    {
        likes++;
    }

    /**
     * Record that a user has withdrawn his/her 'Like' vote.
     */
    public void unlike()
    {
        if (likes > 0) {
            likes--;
        }
    }

    /**
     * Add a comment to this post.
     * 
     * @param text  The new comment to add.
     */
    public void addComment(String text)
    {
        comments.add(text);
    }

    /**
     * Return the time of creation of this post.
     * 
     * @return The post's creation time, as a system time value.
     */
    public long getTimeStamp()
    {
        return timestamp;
    }

    /**
     * Display the details of this post.
     * 
     * (Currently: Print to the text terminal. This is simulating display 
     * in a web browser for now.)
     */
    public void display()
    {
        System.out.println(username);
        System.out.print(timeString(timestamp));

        if(likes > 0) {
            System.out.println("  -  " + likes + " people like this.");
        }
        else {
            System.out.println();
        }

        if(comments.isEmpty()) {
            System.out.println("   No comments.");
        }
        else {
            System.out.println("   " + comments.size() + " comment(s). Click here to view.");
        }
    }

    /**
     * Create a string describing a time point in the past in terms 
     * relative to current time, such as "30 seconds ago" or "7 minutes ago".
     * Currently, only seconds and minutes are used for the string.
     * 
     * @param time  The time value to convert (in system milliseconds)
     * @return      A relative time string for the given time
     */

    private String timeString(long time)
    {
        long current = System.currentTimeMillis();
        long pastMillis = current - time;      // time passed in milliseconds
        long seconds = pastMillis/1000;
        long minutes = seconds/60;
        if(minutes > 0) {
            return minutes + " minutes ago";
        }
        else {
            return seconds + " seconds ago";
        }
    }
}









import java.util.ArrayList;

/**
 * This class stores information about a post in a social network news feed. 
 * The main part of the post consists of a (possibly multi-line)
 * text message. Other data, such as author and time, are also stored.
 * 
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class MessagePost extends Post
{
    private String message;  // an arbitrarily long, multi-line message

    /**
     * Constructor for objects of class MessagePost.
     * 
     * @param author    The username of the author of this post.
     * @param text      The text of this post.
     */
    public MessagePost(String author, String text)
    {
        super(author);
        message = text;
    }

    public static void printShortSummary()
    {
      Post.getUserName();
      System.out.print ("Message postfrom" + username);

    }

    /**
     * Return the text of this post.
     * 
     * @return The post's message text.
     */
    public String getText()
    {
        return message;
    }
}

You should be calling getUserName() but obviously cannot because it returns void and causes a Stack Overflow exception if called: 您应该调用getUserName()但是显然不能,因为调用它会返回void并导致Stack Overflow异常:

public void getUserName()
{
  getUserName();
}

This should be 这应该是

public String getUserName()
{
    return userName;
}

And then that's how you access the user name from the subclass. 这就是从子类访问用户名的方式。

After that you would modify this method to be: 之后,您可以将此方法修改为:

public static void printShortSummary()
{
    //Post.getUserName();
    System.out.print ("Message postfrom" + getUserName());
}

The portion where you have Post.getUserName(); 您拥有Post.getUserName(); doesn't make any sense, it's not a static method and can't be referenced in that manner. 没有任何意义,它不是静态方法,因此无法以这种方式引用。

If you don't have access to Post class or you don't wanna change Post class, you can use java Reflection API to access private members in any class 如果您无权访问Post类或不想更改Post类,则可以使用java Reflection API访问任何类中的私有成员

Ex: 例如:

public void printShortSummary() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    Field field = Post.class.getDeclaredField("username");
    field.setAccessible(true);
    System.out.print("Message post from " + field.get(this).toString());
} 

Note : Anyway this not the object oriented way 注意:无论如何,这不是面向对象的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM