记住这句话:静态方法不能引用非静态变量;
我遇到的是因为将Student 放到了Test类当中去了。
解决的办法:
1.Student类写到Test外边去;
2.Student定义为静态类;
package cn.sxt.oo1;
public class Test {
public static void main(String[] args){
Student student = new Student("lala1",175,"java");
student.rest();
student.study();
}
class Person{
String name;
int height;
public void rest(){
System.out.println("休息一会儿他");
}
}
class Student extends Person{
String major;
public void study(){
System.out.println("有点点想你哦~");
}
public Student(String name,int height,String major){
//天然拥有父类的属性
this.name = name;
this.height = height;
this.major = major;
}
}
}
本文探讨了Java中静态方法不能引用非静态变量的原因,并提供了两种解决方案:一是将类定义在外部,二是将类定义为静态类。通过具体代码示例,详细解释了如何避免在静态上下文中引用实例变量的编译错误。

被折叠的 条评论
为什么被折叠?



