0

If you see my variables for the class everything is private... Then how can I then from this object access the otherAccount followers list in the follow method?

public class TwitterAccount {

    private String name;
    private List<TwitterAccount> follows;
    private List<TwitterAccount> followers;
    private Collection<Tweet> tweetCollections;

    public TwitterAccount(String name) {
        this.name = name;
        follows = new ArrayList<>();
        followers =  new ArrayList<>();
    }

    public String getName() {
        return this.name;
    }

    public void follow(TwitterAccount otherAccount) {
        if(this == account) {
            System.err.println("Can not follow your self");
        }
        this.follows.add(account);
        otherAccount.followers.add(this);
    }
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Henrik
  • 19
  • 2
  • 6
  • https://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html – Guy Mar 27 '18 at 10:08
  • You can access `private` members of class if you are passing object of same class in it. I don't see any problem in your `follow` method except wrong variable name – Vicky Thakor Mar 27 '18 at 10:09
  • If you create otherAccount then no access problem. can you make sure what is account variable here? – Moinul Islam Mar 27 '18 at 10:15

1 Answers1

0

Private members can be accessed inside the class. Looking at your code, you are indeed accessing it inside the class, that's why it is running totally fine.

For experimenting purpose, try to access your private members directly from other class. It won't run.

NOTE: Private members are not directly accessible in other classes, but can be accessed indirectly using getter and setter. So, even if you want to access in other class you can create getter and setter method

Jitindra Fartiyal
  • 107
  • 1
  • 1
  • 5