gpt4 book ai didi

java私有(private)类成员

转载 作者:行者123 更新时间:2023-11-29 03:25:37 25 4
gpt4 key购买 nike

我在套接字教程中遇到过这段代码。首先,我们创建一个数组并将 clientThread 的实例放入其中:

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

我的问题是最后一行代码:threads[i].os.println()。 “os”是一个私有(private)成员,我们怎么可能在它自己的类之外或没有 getter 方法的情况下访问它?

最佳答案

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

关于java私有(private)类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21217854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com