Reputation: 133
How do I pass the tom.name, id age and year variables from the main method into the 'tomdetails' method so that they are recognizable by that method?
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);
}
}
Upvotes: 1
Views: 153
Reputation: 1500515
While you could pass the variables separately, it probably makes more sense to pass the reference to the whole Student
object. For example:
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);
}
The next steps I'd take after that would be:
Student
a constructor accepting the name, ID, age and yearStudent
private (and potentially final), instead exposing data via methods (e.g. getName()
)printDetails()
method within Student
so that you could just call tom.printDetails()
in your main
method.Upvotes: 4
Reputation: 401
I think you can pass just the object tom
:
Change the method to
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);
}
Upvotes: 1