0

I get the typical non static variable cannot be referenced from a static context error when I'm attempting to create a new object. If I make the BookWord class static, everything works. Is that OK in Java?

package javaapplication13;

public class JavaApplication13 {

    public class BookWord {

        private String wordCharacters;
        private int count;

        public BookWord(String word){
            wordCharacters = word;
        }

        public String getWord() {
            return wordCharacters;
        }

        public int getCount() {
            return count;
        }
    }

    public static void main(String[] args) {
        BookWord existing = new BookWord("Hello");  //  *** Error here ***

        System.out.println("The word is " + existing.getWord());
        System.out.println("The current count is " + existing.getCount());

    }
}
baudsp
  • 4,076
  • 1
  • 17
  • 35
  • Please explain why you want BookWord to be nested in the first place because I think that will guide how we answer your question rather than just telling you how to make the build error go away. – nicomp Oct 13 '17 at 15:25
  • Please explain nested in this sense if you don't mind. I was using BookWord as a constructor as it's dictated in a UML diagram. – The Roofer Oct 13 '17 at 15:54
  • 1
    You have a class declared inside a class. The enclosing class for `BookWord` is `JavaApplication1`. BookWord is a member class of JavaApplication1 and is an inner class, meaning that you cannot create an instance of `BookWord` without an instance of JavaApplication1 to which it can be linked. – scottb Oct 13 '17 at 16:15

1 Answers1

1

Class BookWord holds an implicit reference to a JavaApplication13 object. To make it not have such a reference, you should declare it static.

As it stands, BookWord is an inner class, to use official terminology. An inner class is one type of nested class. If you declare BookWord as static, then it's a static nested class. For explanations, see https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42