为什么不能创建内部类的实例?

时间:2018-11-27 07:09:47

标签: java class

我了解了JAVA基本级别。然后,我遇到了一些问题...没有创建内部类实例。

public class example {
    class book {

        private String name = null;
        private int page = 0;

        book(String name, int page) {
            this.name = name;
            this.page = page;
        }

        String getName() {
            return this.name;
        }

        int getPage() {
            return this.page;
        }

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        book b1 = new book("book1", 300);       // this line is making an error
        System.out.println(b1.getName());
        System.out.println(b1.getPage());
        System.out.println();
    }
}

1 个答案:

答案 0 :(得分:1)

您的book类是您的example类的内部类,这意味着它需要一个封闭的example类实例才能实例化(new example().new book("book1", 300))。 / p>

但是,将book类设为非嵌套将更有意义:

class book {
    private String name = null;
    private int page = 0;

    book(String name, int page) {
        this.name = name;
        this.page = page;
    }

    String getName() {
        return this.name;
    }

    int getPage() {
        return this.page;
    } 
}

public class example {  
    public static void main(String[] args) {
        book b1 = new book("book1", 300);
        System.out.println(b1.getName());
        System.out.println(b1.getPage());
        System.out.println();
    }
}