Java:面向对象编程:为什么成员方法不加static

题目

写一个学生类,计算平均成绩
一个grade();是在main方法里写的直接调用
一个cj();是在实体类写的打点调用,因为算是成员方法
注意理解

位置

在这里插入图片描述

代码

Student.java

package com.zhang.opp;

/**
 * @Author: ggdpzhk
 * @CreateTime: 2024-08-05
 */
public class Student {
    String name;
    int chinese,math;

    public Student(String name, int chinese, int math) {
        this.name = name;
        this.chinese = chinese;
        this.math = math;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", chinese=" + chinese +
                ", math=" + math +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getChinese() {
        return chinese;
    }

    public void setChinese(int chinese) {
        this.chinese = chinese;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }

    public double cj() {
        return (chinese+math)/2;
    }
}

Test.java

package com.zhang.opp;

/**
 * @Author: ggdpzhk
 * @CreateTime: 2024-08-05
 */
public class Test {

    public static double grade(Student st){
        return (st.chinese+st.math)/2;
    }

    public static void main(String[] args) {
        Student s1 = new Student("张三",100,98);
        System.out.println(s1);
        double grade = grade(s1);
        System.out.println(grade);


        Student s2 = new Student();
        s2.name = "李四";
        s2.chinese = 90;
        s2.math = 80;

        System.out.println(s2);
        double cj = s2.cj();
        System.out.println(cj);

    }
}

运行结果

在这里插入图片描述

为什么成员方法不加static

在这里插入图片描述

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值