我正在尝试编写一个需要在类的另一个方法中使用对象的类,请考虑伪代码:
class socket {
private (something to be used by other methods) interface_like_method {
//initializing a socket class
//to be used by other methods
}
public FileTrasfer (ref socket client) {
// here, we can use the initialized obj of interface_like_method
// client.sendfile("a path") ;
}
}
如何实现这样的功能?
答案 0 :(得分:3)
将变量声明为'实例变量' (也称为'成员变量')。这意味着该变量可以在类中的任何位置使用。如果变量是在方法中声明的,那么只有该方法才能访问它。
class One {
//code
}
class Two {
One one; //instance variable accessible in entire class, not initialized
One oneInitialized = new One(); //this one is initialized
Two() { //this is a constructor
one = new One(); //initializes the object 'one' that is declared above
}
someMethod() {
One secondOne = new One(); //can only be used inside this method
}
//use object 'one' anywhere;
}