public class Test{
int number = 1;
String text = "hello";
public int method1() {
return number + 1;
}
public String method2() {
return text + " moo";
}
}
public class MyClass {
private String myString; // this variable can only be directly access from within MyClass scope.
// constructor - called when an instance of MyClass is initialized ( e.g. MyClass myClass = new MyClass(); )
public MyClass(){
myString = "Hello world!"; // init my_string
}
// Can access variable from within class to print
public void printMyString(){
System.out.println(myString);
}
// Can set private class variables
public void setMyString(String input){
this.myString = input; // set value
}
// Can get (return) private class variables
public String getMyString(){
return myString; // get value
}
}
从程序的另一部分:
MyClass myClass = new MyClass(); // init class (calls constructor)
System.out.println(myClass.getMyString()); // prints "Hello world!"
myClass.setMyString("Hola"); // changes value of myString
System.out.println(myClass.getMyString()); // prints "Hola"
System.out.println(myClass.myString); // Error: cannot directly access private variable of java class MyClass.
# 1 楼答案
应该在多个方法中可用的变量应该在类的顶部声明,如下所示
或者,如果您有另一个变量与其中一个全局变量同名,您可以使用类似
this.number
的内容引用全局变量# 2 楼答案
通常最推荐的方法是将对象从一个方法转移到另一个方法。这有助于保持代码模块化并减少耦合。Java中的一个常见概念是自定义类的getter和setter。见下面的例子:
从程序的另一部分: