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

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

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

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

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

猜你喜欢

转载自blog.csdn.net/m0_54066656/article/details/127326930
今日推荐