someGuy
someGuy

Reputation: 77

Make 3 classes call one another

So I'm trying to figure out how can I have 3 classes call one another.

this is the main class.

public class TestStudent {
    public static void main(String[] args) {
        myStudent mystudent_obj = new myStudent();
        mystudent_obj.show_grades();
        mystudent_obj.change_grades();
        mystudent_obj.show_grades();
    }
}

This is the 2nd class that's being called in the class above; The 2nd class call another 3rd class and try to manipulate it using two functions. Function show_grades just print out the variables in the 3rd class and function change_grade try to change the variables in the 3rd class.

public class myStudent {
    public void show_grades(){
        Student student_obj = new Student();
        System.out.println(student_obj.studGrade);
        System.out.println(student_obj.studID);
    }

    public void change_grades(){
        Student student_obj = new Student();
        student_obj.studGrade='V';
        student_obj.studID=10;
    }
}

This the 3rd call, which only has two variables.

public class Student {
    public int studID = 0;
    public char studGrade = 'F';
}

when I run the program it runs without errors and I get an output of:

F
0
F
0

however, I can see that the function show_grades work and it does display the grades, but the function change_grades does not change the grades:

The end results, should be something like this

F
0
V
10

because the change grade function, should have changed those variables... so what's going on?

Upvotes: 2

Views: 1554

Answers (1)

Patrick
Patrick

Reputation: 17973

In your myStudent class you are creating a new instance of Student in each method, meaning that each method has a local variable of class Student. When you call show_grades the second time, a new instance is created, with the default values of 0 and F.

If you create a variable and use that instead, your change grades will change the variables of the instance variable instead of a local variable in each method. This is due to scoping in programming, which you can read more about at Wikipedia.

public class myStudent {
    private Student student_obj = new Student();

    public void show_grades() {
       System.out.println(student_obj.studGrade);
       System.out.println(student_obj.studID);
    }

    public void change_grades(){
        student_obj.studGrade='V';
        student_obj.studID=10;
    }
}

Upvotes: 3

Related Questions