Discuss / Java / 这段不会报错吗。。。

这段不会报错吗。。。

Topic source

不是,这段代码,真的不会报错吗。。。

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Xiao Ming", 12, 89);
    }
}

class Person {
    protected String name;
    protected int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

class Student extends Person {
    protected int score;

    public Student(String name, int age, int score) {
        super(name, age);  // 调用父类的构造方法Person(String, int)
        this.score = score;
    }
}

错误: 无法从静态上下文中引用非静态 变量 this

        Student s = new Student("Xiao Ming", 12, 89);

要改成这样吧

static class Person{}

static class Student extends Person{}

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

仔细检查你的代码,看看是不是把Student写到Main里面去了。

果然是,谢谢老师指正。XD

心云意水

#4 Created at ... [Delete] [Delete and Lock User]

看了几遍,没觉得这段代码会报错啊?lz是修改过了嘛?


  • 1

Reply