2015-06-15 74 views
-4

我要访问像开放所有功能),SSC(和bind()以及我要访问的功能变量在同一类的不同功能

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); 
}` 
+0

@Odedra无论是什么?它已被回答,并且真的不需要更多这种东西。 – laune

+0

我认为解决方案是阅读您的教学文本。这是一个基本的发展宗旨,所关心的是你花费了零时间学习,而不是在你的“学习”体验中询问每个基本问题。 – KevinDTimm

回答

1

由于scc被声明为一个局部变量它不能用其他方法访问。它需要在课堂上进行宣布。

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

你应该把它定义为一个全局变量不是本地的createSocket()你将只能使用它在createSocket()范围你现在定义方式。你需要使它成为一个class级别的变量。

0

因此,在定义这些方法的类范围中定义它。例如:

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

然后你可以参考他们如:

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