java 类中 static 成员变量

写出运行结果

class Student{
    static String school;
    String name;
    static int score;
    Student(String name){
        this.name = name;
    }
    int sum(int score){
        score += score;
        return score;
    }
    void print(){
        System.out.println(school + "," + name + "," + score);
    }
}

public class Test {
    public static void main(String[] args) {
//两句在堆中分配了两个 Student 类内存空间,stu1 的 name 为”小明”, stu2 的 name 为”小王”。
        Student stu1 = new Student("小明");
        Student stu2 = new Student("小王");
//因为在 Student 类中 school 的是类成员,所有对象共享,使得 stu1、stu2 的 school 均是“**大学”。 
        Student.school = "**大学";
/*Student 类中 static int score 是一个成员变量,而 int sum(int score)中的 score 仅是一个函数参数变量,
由于sum 函数中没有使用this进行全局,导致sum 函数内的所有操作仅在函数内有效,不会改变函数外的 score 变量, 
而 int 类型的类初始值是 0,故这两句代码执行结束之后,stu1 和 stu2 的成员变量 score 依旧是 0。*/
        stu1.sum(20);
        stu2.sum(30);
//打印出 school + "," + name + "," + score
        stu1.print();
        stu2.print();
    }
}
**大学,小明,0
**大学,小王,0
posted @ 2021-07-09 20:22  SKPrimin  阅读(78)  评论(0编辑  收藏  举报