Java中为什么不能把Person类放到Demo8类里面

class Demo8{

    class Person{

        int id; //编号

        String name; //姓名

        int age;  //年龄

        //构造函数
        public Person(int id,String name ,int age){
            this.id  = id;
            this.name = name;
            this.age = age;
        }

        //比较年龄的方法
        public void compareAge(Person p2){
            if(this.age>p2.age){
                System.out.println(this.name+"大!");
            }else if(this.age<p2.age){
                System.out.println(p2.name+"大!");
            }else{
                System.out.println("同龄");
            }
        }
    }

    public static void main(String[] args) 
    {
        Person p1 = new Person(110,"狗娃",17);
        Person p2 = new Person(119,"铁蛋",9);
        p1.compareAge(p2);

    }
}


其实是java虚拟机运行时对class的解析与实例化的时机(顺序)问题。对于程序入口函数main来说,在它被调用时还“看”不到内部类Person呢。
解决方法有两个,一是将Person声明为static,二是将Person声明为外部类。

https://www.cnblogs.com/runnigwolf/p/5570810.html

这个是可以放的,内部类
但是main方法应该是在外部类
但是你不能再main方法中去实例化person。
你可以写个方法去实例化person
然后再main方法里调用你写的外部类的方法

这个是内部类实例化问题,必须依赖一个外部类的实例才能创建内部类的实例,修改main如下即可:


    public static void main(String[] args) 
    {
        Demo8 d = new Demo8();
        Person p1 = d.new Person(110,"狗娃",17);
        Person p2 = d.new Person(119,"铁蛋",9);
        p1.compareAge(p2);

    }

把Demo8里面的子类Person申明为静态类即可。

public class Demo8 {

    static class Person{

        int id; //编号

        String name; //姓名

        int age;  //年龄

        //构造函数
        public Person(int id,String name ,int age){
            this.id  = id;
            this.name = name;
            this.age = age;
        }

        //比较年龄的方法
        public void compareAge(Person p2){
            if(this.age>p2.age){
                System.out.println(this.name+"大!");
            }else if(this.age<p2.age){
                System.out.println(p2.name+"大!");
            }else{
                System.out.println("同龄");
            }
        }
    }

    public static void main(String[] args)
    {
        Person p1 = new Person(110,"狗娃",17);
        Person p2 = new Person(119,"铁蛋",9);
        p1.compareAge(p2);

    }
}