2014-01-19 79 views
1

我在sockets教程中遇到了这个代码。 首先,我们在它创建一个数组,并把clientThread的实例:java私有类成员

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; 
      } 
     } 

这里是clientThread类(的一部分):

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"); 
     } 
     } 

我的问题是代码的最后一行:线程[I] .os.println()。 'os'是一个私人成员,我们如何在它自己的类之外访问它,或者没有getter方法?

+0

run方法是clientThread的成员。为什么它不能访问clientThread实例上的私有成员操作系统? – odedsh

+1

@lakshman - 这里没有反映,也没有必要。 –

+0

据我所知,它属于自己的类... –

回答

4

它适用于os,因为一个实例可以访问同一类的其他实例的私有成员。 Java中的访问控制是在类级别而不是在实例级别上确定的。例如,Scala使用修饰符private[this]将成员标记为实例级私有成员。

+0

为什么人们不会阅读完整的问题?这就是所谓的阴影。 – Troubleshoot

+0

@Troubleshoot:我阅读了整个问题......谨慎解释你的想法? –

+0

有没有其他人确认这个答案?如果来自同一个班级,您可以访问其他对象的私人成员? –