java 类中 static 成员变量

75 篇文章 2 订阅

写出运行结果

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SK Primin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值