Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my inner class DO see a NON static variable?

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

}
like image 558
Roman Avatar asked Dec 03 '25 10:12

Roman


1 Answers

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:)

like image 143
Petar Minchev Avatar answered Dec 05 '25 00:12

Petar Minchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!