2

所以我想弄清楚如何让 3 个班级互相调用。

这是主要课程。

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();
    }
}

这是在上面的类中调用的第二类;第二类调用另一个第三类并尝试使用两个函数对其进行操作。函数show_grades只是打印出第 3 类中的变量,然后函数change_grade尝试更改第 3 类中的变量。

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;
    }
}

这是第三次调用,它只有两个变量。

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

当我运行程序时,它运行时没有错误,我得到以下输出:

F
0
F
0

但是,我可以看到该功能show_grades有效并且确实显示了成绩,但该功能change_grades不会更改成绩:

最终结果,应该是这样的

F
0
V
10

因为改变等级功能,应该改变了那些变量......那是怎么回事?

4

1 回答 1

3

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;
    }
}
于 2012-04-07T22:27:26.057 回答