[英]How do you pass variables to different methods
如何將主方法中的 tom.name、id 年齡和年份變量傳遞給“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
object 可能更有意義。 例如:
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
中的所有字段設為私有(可能是最終字段),而不是通過方法(例如getName()
)公開數據Student
中添加一個printDetails()
方法,以便您可以在main
方法中調用tom.printDetails()
。我認為您可以只傳遞 object tom
:將方法更改為
private static void tom_details(Student tom) {
System.out.println(tom.name);
System.out.println(tom.id);
System.out.println(tom.age);
System.out.println(tom.year);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.