package pl.codegym.task.task06.task0615;
/*
Feng Shui i statyczne
*/
public class Solution {
public int A = 5;
public int B = 2;
public static int C = A * B;
public static void main(String[] args) {
A = 15;
}
}
Dlaczego A musi być statyczne a B już nie ? Do tej pory nie mogę tego zrozumieć 😥
Rozwiązane
Komentarze (3)
- Popularne
- Najnowsze
- Najstarsze
Musisz się zalogować, aby dodać komentarz
Guadalupe Gagnon
13 lutego, 14:34
First let me start by saying that variables that exist within the class code but not inside a method are called fields or class variables. I use fields in the following explanation.
The task says to move one static modifier so that the code compiles. The static modifier marks fields, methods, and contained classes as object independent. This means that they can be used without having to create an object first. Further, static fields are created when the class code is read into memory, which occurs before any objects of that class are created.
Looking at this code as it shows that Line 11, the field 'C', is static. It is initialized to the value of 'A * B'. As I mentioned above about static variables are created before any objects of that class are, because 'A' and 'B' are not static they do not exist at the time that 'C' is created and initialized. Therefore this line of code is illegal and it is always illegal to pre-initialize static variables using non-static variables. For this code to compile both A and B would need to be static, but that is not what the task asks you to fix.
Now, similarly, static methods exist without any objects. In the same sense that static variables cannot be pre-initialized with non-static variables, static methods cannot use non static fields. Therefore line 14, the use of the non-static field 'A' within a static method, is illegal and would prevent the code from compiling.
**You probably haven't realized this, since you are learning, but the println() method that you have used in a number of tasks already is a static method. This is opposed to the readLine() method that is used for keyboard input and requires you to make a BufferedReader object to use.**
+2
Guadalupe Gagnon
13 lutego, 14:53rozwiązanie
Considering all that information, and the task requirement to move only 1 static modifier to make the code legal, you are left with only being able to change the static modifier on the field 'C' to either 'A' or 'B'.
Imagine if we changed the static modifier to the 'B' field instead. Line 9 would be acceptable. Line 10 would be acceptable. Line 11 would be acceptable because 'C' would non-static and non-static fields can use any other type of field or combination of types. Line 14 would not be valid because it is a static method using a non-static field (which is illegal).
If we instead changed the static modifier to the 'A' field then lines 9, 10, and 11 would all be valid and line 14 would be valid too.
+2
MichałExpert
13 lutego, 19:32
Thank you very much. You helped me a lot :)
0