public class Person {
public String name; public int age; public void dining() { System.out.println("吃饱了..."); } class Student extends Person{ public int xuehao; public void ss(){ System.out.println("student"+name+age+xuehao); } } class teacher extends Person{ public int grade; public void tt(){ System.out.println("teacher"+name+age+grade); } }public static void main(String[] args) {
// TODO Auto-generated method stub Student stu=new Student();}
}
实例化对象的时候提示错误:
No enclosing instance of type Person is accessible. Must qualify the allocation with an enclosing instance of type Person (e.g. x.new A() where x is an instance of Person).
原因:我写的内部类是动态的,也就是开头以public class开头。而主程序是public static class main。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。
解决方法:1、将内部类修饰为静态类:static class Student extends Person{}; static class teacher extends Person{};
2、实例化改为 【new 外部类().new 内部类()】即 Student stu=new Person().new Student();