如何将 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);
}
}
最佳答案
虽然您可以单独传递变量,但传递对整个Student
对象的引用可能更有意义。例如:
public static void main(String[] args) {
Student tom = new Student();
tom.name = "Tom";
tom.id = 1;
tom.age = 15;
tom.year = 10;
printDetails(tom);
}
private static void printDetails(Student student) {
System.out.println(student.name);
System.out.println(student.id);
System.out.println(student.age);
System.out.println(student.year);
}
在那之后我要采取的下一步是:
- 给
Student
一个接受姓名、ID、年龄和年份的构造函数 - 将
Student
中的所有字段设为私有(private)(并且可能是最终的),而不是通过方法(例如getName()
)公开数据< - 可能在
Student
中添加一个printDetails()
方法,这样您就可以在main 中调用
方法。tom.printDetails()
关于java - 如何将变量传递给不同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58354574/