I got verification/passed using the below, but why? How? I just guessed.
And what does this do? A=15;
public class Solution {
public static int A = 5;
public int B = 2;
public int C = A * B;
public static void main(String[] args) {
A = 15;
}
}
Kent Hervey
Level 16
Please explain why it works
Under discussion
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
25 October 2019, 13:50useful
At line 21 the setting of A to 15 is being done in a static context, which means that no object has been created to access A. It would be like if you just typed:
in your code without declaring a reader object and initializing it. The only way that you can do this statically with methods and variables is if in the class they are declared as static. I don't know if you have caught this yet, you can look back at all your code, but any method in the Solution class that you have made has had the static keyword. Remove it and you code will not compile. If you did this then you would have to change the rest of your code to make Solution objects to access the method. So, without static, this code would have to be:
This would compile, though not satisfy the task requirements. +3
Kent Hervey Software Engineer/Consult at Zeal IT ConsultantsExpert
25 October 2019, 22:17
Thanks. I am still struggling with this one. I will revisit your answer.
BTW, when you say: any method in the Solution class that you have made has had the static
Only if they need to be static..right...if I went all the way back to before we had static exercises and were using non-static methods....for instance/object work, then they would not be there??
0
Guadalupe Gagnon
26 October 2019, 04:29
The only way a method works is:
A) you create an object that has the method, for example:
B) you just use a method, however the code will not compile unless that method is static, an example:
0
Guadalupe Gagnon
26 October 2019, 04:31
So, if you had a method in any code that you did prior and used it without creating an object, then it 100% has the static keyword as part of the method declaration. The code would not compile otherwise. Also notice that the main() method (yes it is a method) is static too.
+1