I study on the sly Java according to the book Head First Java.

In Chapter 4, I completed the task, in my opinion correctly (I looked at the answers in the book - my solution is the same). But, nevertheless, a compile error occurs:

non static variable cannot be referenced from a static context

in line 10:

obs[x] = new Puzzle4b(); 

Code:

 public class Puzzle4{ public static void main(String[] args){ Puzzle4b[] obs = new Puzzle4b[6]; int y=1; int x = 0; int result = 0; while(x < 6){ obs[x] = new Puzzle4b(); obs[x].ivar = y; y=y*10; x = x+1; } x = 6; while(x > 6){ x = x-1; result = result + obs[x].doStuff(x); } System.out. print("Result "+ result); } class Puzzle4b { int ivar; public int doStuff(int factor){ if(ivar>100){ return ivar*factor; } else { return ivar*(5 - factor); } } } } 

What is higher gives an empty result (zero). And should 543345

What is my mistake?

  • It is not strange, this code I ran without any errors. - Ep1demic
  • I manually launch via javac, version 1.8.0_31 - Andrey Vladislavovich
  • one
    You show us the wrong code that you run. If you run the compiler from the command line, then check that all files in the editor are saved. - Boris T
  • Well, then, I think it's time to switch to IDE;)) In my opinion, using cmd does not help studying and does not add coolness, but simply inconvenience and time wasting;) - Ep1demic
  • In the code above, the indicated error cannot occur. But there are logical errors. - user194374

2 answers 2

The error occurs because you are trying to create an instance of the inner class ( inner class ) in the static method of the outer class ( outer class ) - this is not possible.

An instance of the inner class can only be created in the non-static method of the outer class, in other words, with an instance of the outer class.

If you want to create an instance of the Puzzle4b class in the static method of the outer class, then the Puzzle4b class Puzzle4b be declared static ( static nested class ):

 static class Puzzle4b { int ivar; public int doStuff(int factor){ if(ivar>100){ return ivar*factor; } else { return ivar*(5 - factor); } } } 

You can read more in any (better than the classic) book on Java in the chapter where internal classes are described.

What is higher gives an empty result (zero). And should 543345

Look closely at the code snippet where you change the result variable:

 x = 6; while(x > 6) { x = x-1; result = result + obs[x].doStuff(x); } 

The while(x > 6) {...} does not run once, since 6 > 6 == false , therefore, when outputting to the console, it will contain the value that you initially initialized this variable to:

 int result = 0; 
  • Exactly, it was necessary to set the condition x> 0! Then my first option would work successfully when I pulled the class outside. - Andrey Vladislavovich
  • Strange, but there was not a word about static in the book, apparently the task is incorrect. - Andrey Vladislavovich
  • It turns out from a static method it is impossible to cause not static. But I called obs [x] = new Puzzle4b (); in static void main, and class Puzzle4b is not in it. Why is that? - Andrey Vladislavovich
  • @AndreyVladislavovich, I am very skeptical of the books from the Head First series, I think it's better to read Schildt in Java. - post_zeew
  • @AndreyVladislavovich, Everything I said - I talked about inner classes. If you brought the Puzzle4b class anywhere from the Puzzle4 class, then the Puzzle4b class is no Puzzle4b internal. - post_zeew

Java is an object-oriented language. Through new you create instances of objects of a certain class. But a class is also an object in essence, which takes place in the memory and to which you can get a link.

When a program writes a .class file, it divides all variables in the class into two parts. static will be written to the class object. This type of variable will increase the size of the class itself. The class object is one in memory and is loaded once and for the entire duration of the operation. Accordingly, the static variable is one per class and, accordingly, one for all created objects of this class.

Non-static variables will be written to the generated objects, for each generated object there will be its own independent set of these variables that can be manipulated independently of each other.

So here. At the time the program starts, only the class is loaded. There is not a single instance of the object until you create it with new. There are no non-static variables that are stored in objects, and there is also no place for them in RAM. They have nowhere to read and write. Therefore, the program curses that you are trying to access non-static variables from a static function.

PS Here, for example, you are automating a single dispatching system of airports in the country. The specific density of kerosene is the same for all airports. That is, from the volume of fuel purchased, you can calculate its weight at any time, without knowing anything about a particular airport. Density is a static quantity. And the length of the runway and the number of parking on the platform - for each airport has its own. Until you create an instance of the airport through new and download the information from the database, you will not be able to operate with these values. Without a selected airport, the number of parking areas is an abstract concept that makes no sense.

  • one
    Read the question carefully. In the code there are no calls to non-static objects from static methods. Error to this code obviously has nothing to do. - user194374
  • Thanks, about static classes very well told. In the book, the truth is not even a word about them. - Andrey Vladislavovich