为什么我的内部类确实看到非静态变量?
早些时候,当内部匿名类看不到“外部”类的字段时,我遇到了一个问题。我需要创建一个最终变量以使其对内部类可见。现在我的情况正好相反。在“外部”类“ClientListener”中,我使用内部类“Thread”,“Thread”类我有“run”方法,并且确实从“外部”类中看到了“earPort”!为什么?
import java.io.IOException;
import java.net.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ClientsListener {
private int earPort;
// Constructor.
public ClientsListener(int earPort) {
this.earPort = earPort;
}
public void starListening() {
Thread inputStreamsGenerator = new Thread() {
public void run() {
System.out.println(earPort);
try {
System.out.println(earPort);
ServerSocket listeningSocket = new ServerSocket(earPort);
Socket serverSideSocket = listeningSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(serverSideSocket.getInputStream()));
} catch (IOException e) {
System.out.println("");
}
}
};
inputStreamsGenerator.start();
}
}
Earlier I had a problem when an inner anonymous class did not see a field of the "outer" class. I needed to make a final variable to make it visible to the inner class. Now I have an opposite situation. In the "outer" class "ClientListener" I use an inner class "Thread" and the "Thread" class I have the "run" method and does see the "earPort" from the "outer" class! Why?
import java.io.IOException;
import java.net.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ClientsListener {
private int earPort;
// Constructor.
public ClientsListener(int earPort) {
this.earPort = earPort;
}
public void starListening() {
Thread inputStreamsGenerator = new Thread() {
public void run() {
System.out.println(earPort);
try {
System.out.println(earPort);
ServerSocket listeningSocket = new ServerSocket(earPort);
Socket serverSideSocket = listeningSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(serverSideSocket.getInputStream()));
} catch (IOException e) {
System.out.println("");
}
}
};
inputStreamsGenerator.start();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
匿名内部类可以访问静态变量和实例变量。如果您还想访问局部变量,请将它们声明为final。这就是它的工作原理:)
Anonymous inner classes have access to static and instance variables. If you want to have also access to local variables, declare them as final. This is how it works:)
您的匿名内部类可以访问包含对象的属性。所有未声明为静态的内部类都具有隐式访问器。
如果你想防止这种情况发生,你可以声明一个静态内部类并实例化它:
Your anonymous inner class has access to the attributes of the containing object. All inner classes that are not declared
static
have an implicit accessor.If you want to prevent this from happening, you can declare a static inner class and instantiate that: