简体   繁体   中英

java private class member

I faced this code in a sockets tutorial. First we create an array and put instances of clientThread in it:

public class MultiThreadChatServer {
...
private static final clientThread[] threads = new clientThread[maxClientsCount];
...
clientSocket = serverSocket.accept();
        int i = 0;
        for (i = 0; i < maxClientsCount; i++) {
          if (threads[i] == null) {
            (threads[i] = new clientThread(clientSocket, threads)).start();
            break;
          }
        }

And here is the clientThread class(part of it):

class clientThread extends Thread {

  private DataInputStream is = null;
  private PrintStream os = null;
  private Socket clientSocket = null;
  private final clientThread[] threads;
  private int maxClientsCount;

  public clientThread(Socket clientSocket, clientThread[] threads) {
    this.clientSocket = clientSocket;
    this.threads = threads;
    maxClientsCount = threads.length;
  }

  public void run() {
    int maxClientsCount = this.maxClientsCount;
    clientThread[] threads = this.threads;

    try {
      /*
       * Create input and output streams for this client.
       */
      is = new DataInputStream(clientSocket.getInputStream());
      os = new PrintStream(clientSocket.getOutputStream());
      os.println("Enter your name.");
      String name = is.readLine().trim();
      os.println("Hello " + name
          + " to our chat room.\nTo leave enter /quit in a new line");
      for (int i = 0; i < maxClientsCount; i++) {
        if (threads[i] != null && threads[i] != this) {
          threads[i].os.println("A new user"+name+"entered the chat room");
        }
      }

My problem is with the last line of code: threads[i].os.println(). 'os' is a private member, how is it possible we are accessing it outside it's own class or without a getter method?

It works for os because an instance can access private members of other instances of the same class. Access control in Java is determined at the class level, not at the instance level. Scala, for example, has the modifier private[this] to mark a member as instance-level private.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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