【发布时间】:2019-10-12 13:19:01
【问题描述】:
如何将 tom.name、id age 和 year 变量从 main 方法传递到 'tomdetails' 方法中,以便该方法可以识别它们?
class Student {
int id;
int age;
int year;
String name;
}
class Staff {
int id;
int age;
String name;
String postcode;
String department;
}
public class Main {
public static void main(String[] args) {
//Database
//Students
Student tom = new Student();
tom.name = "Tom";
tom.id = 1;
tom.age = 15;
tom.year = 10;
}
private static void tom_details() {
System.out.println(tom.name);
System.out.println(tom.id);
System.out.println(tom.age);
System.out.println(tom.year);
}
}
【问题讨论】:
-
我建议阅读有关方法的教程,例如this one by oracle.
-
对象“tom”对于 main() 方法是本地的。该对象只能在 main() 方法中访问。所以你不能访问范围之外的本地成员,即在 tom_details() 方法内。
-
这个问题的两个解决方案。 1) 将“tom”对象传递给 tom_details() 方法。 2) 用“static”关键字在主类中全局声明“tom”对象。
标签: java