shadowByte
shadowByte

Reputation: 133

How do you pass variables to different methods

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

Answers (2)

Jon Skeet
Jon Skeet

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:

  • Give Student a constructor accepting the name, ID, age and year
  • Make all the fields within Student private (and potentially final), instead exposing data via methods (e.g. getName())
  • Potentially add a printDetails() method within Student so that you could just call tom.printDetails() in your main method.

Upvotes: 4

Daniel Nudelman
Daniel Nudelman

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

Related Questions