I want to access variable of function in different function of same class

时间:2015-06-15 14:26:33

标签: java

i want to access ssc in all the functions like open() and bind() as well

public void createSocket()
{
    ServerSocketChannel ssc = null;
}    
public void openSocket() throws IOException
{
    ssc = ServerSocketChannel.open();
}    
public void bind()    
{
    ssc.socket().bind(new InetSocketAddress(8888));
    ssc.configureBlocking(false);
}`

3 个答案:

答案 0 :(得分:1)

Since scc is declared as a local variable it cannot be access in other methods. It needs to be declared at the class level.

public OuterClass {
    private ServerSocketChannel ssc = null; << Class level declaration

    public void createSocket()
    {
        ssc = null;
    }    

    public void openSocket() throws IOException
    {
        ssc = ServerSocketChannel.open();
    }    

    public void bind()    
    {
        ssc.socket().bind(new InetSocketAddress(8888));
        ssc.configureBlocking(false);
    }
}

答案 1 :(得分:0)

You should define it as a global variable not local to createSocket() you will only be able to use it in the createSocket() scope the way you have it defined now. You need to make it a class level variable.

答案 2 :(得分:0)

So define it in the class scope where these methods are defined. For example:

public class MySocketClass {

   private ServerSocketChannel ssc;

   public void createSocket() {
      // this method now seems redundant; consider replacing this functionality
      // in the default constructor for this class
      ssc = null;
   }

    public void openSocket() throws IOException {
        ssc = ServerSocketChannel.open();
    }

    public void bind() {
        ssc.socket().bind(new InetSocketAddress(8888));
        ssc.configureBlocking(false);
    }
}

And then you can reference them such as:

MySocketClass msc = new MySocketClass();
msc.openSocket();
msc.bind();