2

I learnt about JAVA basic level. Then, I meet some problem... the inner class instance is not created.

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();
    }
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
서현석
  • 23
  • 3

1 Answers1

1

Your book class is an inner class of your example class, which means it requires an enclosing example class instance in order to be instantiated (new example().new book("book1", 300)).

However, it would make more sense to make the book class not-nested:

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();
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768