Java error Cannot make a static reference to the non-static method - cannot refer to a non-static method from a static context.

When writing inheritance-related practice code, I encountered the following problems:

Cannot make a static reference to the non-static method show() from the type Student (translation means that it is impossible to make static references to non-static methods), I believe that the first thought of many people is to add static to the show method in Student , that is, convert this class into a static method, but in fact this is not possible. If it is removed, the show method in the parent class cannot be inherited and overridden, so we have to see if there are other errors.

Please see the screenshot for details:

Note that I created a new student object, but I still use the show method of the Student class instead of using the show method through the student object, so the compiler will report an error Cannot make a static reference to the non-static method show() from the type Student, at this point we only need to change Student to student.

The detailed code is as follows:

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

In fact, I also mentioned this error in the previous sharing. For details, please refer to:

Cannot refer to a non-static method from a static context

Guess you like

Origin blog.csdn.net/m0_54066656/article/details/127326930