Java报错Cannot make a static reference to the non-static method——无法从静态上下文中引用非静态方法。

本文解析了在Java中尝试静态引用非静态方法show()时出现的错误,并提供了正确的代码示例来解决这一问题。

在写继承相关练习代码时,遇到以下问题:

Cannot make a static reference to the non-static method show() from the type Student(翻译过来就是无法对非静态方法的进行静态引用),相信很多人第一个想法就是在Student里面的show方法加上static,也就是将这个类转化为静态方法,但是实际上这个是不可以的。如果去掉的话,就无法继承和重载父类中的show方法了,因此我们得看看是不是别的错误。

详情请看截图:

注意看,我新建了一个student对象,但是我用的还是通过类Student的show方法,而不是通过student对象去使用这个show的方法,所以编译器就会报错Cannot make a static reference to the non-static method show() from the type Student,此时我们只需要将Student改为student就行了。

详细代码如下:

public class Person {
    String name;
    char sex;
    int age;
    // 构造函数,设置父类person对象信息
    public Person(String name, char sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    //输出父类person对象信息
    public String show() {
        return "姓名:" + name + ", 性别:"+ sex + ", 年龄:" + age;
    }
}

public class Student extends Person {

    int id;

    public Student(String name, char sex, int age,int id) {
        super(name, sex, age);
        this.id = id;
    }

    @Override
    public String show() {
        return super.show()+ name + age + sex + id;
    }
}
public class PersonApp {
	
    public static void main(String[] args) {
        Person person=new Person("小明",'男',20);
        System.out.println(person.show());
        
        Student student=new Student("小天",'男',21,143);
        System.out.println(student.show());
    }
}

其实这个错误,我在之前的分享中也提到了,详情可以参考:

无法从静态上下文中引用非静态方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值