java - 在循环里一直new对象为什么是可以的?
天蓬老师
天蓬老师 2017-04-17 17:26:53
0
6
883

菜鸟一枚,如果问题问的不恰当请各位轻喷。
第二次编辑:抱歉各位!我似乎误导了大家!
在学习客户端与服务器端的通信时,当中这么一段代码:

while(true){
//等待客户端的连接
socket = serverSocket.accept();
//创建一个新的线程
ServerThread serverThread = new ServerThread(socket);
    //启动线程
serverThread.start();
}

我想问:为什么一个同名对象能一直被new出来(当客户端建立起一个连接时)?比如这个serverThread。
但是如果我这么写:

while(true){
//等待客户端的连接
socket = serverSocket.accept();
//创建一个新的线程
ServerThread serverThread = new ServerThread(socket);
    ServerThread serverThread = new ServerThread(socket);
    //启动线程
serverThread.start();
}

我知道这是错的,new相同名字的对象是不可以的。
但是在无限循环中,也是在不停的new出对象啊,ServerThread serverThread = new ServerThread(socket);
不停的被执行,serverThread不停的创建..这样为什么可以呢?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(6)
PHPzhong

Objects have scope. For example, the serverThread in the first loop will be destroyed when the loop ends. That is, it belongs to the same role between "{" and "}" in while (true) {...} domain.

Ty80

C language is block scope, as long as you write a { }就会生成一级作用域。所以serverThread local variable similar to a function. Each loop is a different call to the function, so there won't be any problems.

大家讲道理

Each loop can be used as a scope. The second one is that there are two identical variable names in the same scope, which is definitely not possible.
Just change the name of the second variable.
Supplement: Your variable is a local variable inside the loop. You can think of it this way: this loop and the next loop are not in the same scope, so you essentially created the same name in different scopes. variable.

大家讲道理
while (true) {
    int localValue = 100;
    // int localValue = 200; // ERROR!在当前作用域,已经存在名为 localValue 的变量,不可重复声明变量
}

int localValue = 200; // OK!当前作用域没有名为 localValue 的变量
伊谢尔伦

In fact, this is just a repeated variable declaration error

ServerThread serverThread = new ServerThread(socket);
//serverThread 已经被声明你是无法再次声明。
serverThread = new ServerThread(socket);

If you say this, it is the same as what everyone said. The serverThread variable will actually be destroyed after a loop. When you come to
ServerThread serverThread = new ServerThread(socket);
, serverThread actually no longer exists, so it can be Restate

黄舟

A variable that already exists in the same scope cannot be declared repeatedly, but this is possible:
Class A{
Int a = 0;
void methodB(){

  Int a = 1;

}
}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template