2014-01-19 84 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

有沒有其他人確認這個答案?如果來自同一個班級,您可以訪問其他對象的私人成員? –