public class Solution {
public static int schritt;
public static void main(String[] args) {
methode1();
}
public static void methode1() {
methode2();
}
public static void methode2() {
new Solution().methode3();
}
public void methode3() {
methode4();
}
public void methode4() {
schritt++;
for (StackTraceElement element : Thread.currentThread().getStackTrace())
System.out.println(element);
if (schritt > 1)
return;
main(null);
}
}
hidden #10625598
Level 23
warum kann Methode 4 auf den statischen int zugreifen, und warum muss Methode 4 nicht statisch sein? Methode 3 greift darauf zu, genau so wie Methode 2 auf 3 und 1 auf 2?
Gelöst
Kommentare (3)
- Beliebt
- Neu
- Alt
Du musst angemeldet sein, um einen Kommentar schreiben zu können
Gellert Varga
20 Mai 2020, 20:32
Little clarifying:Which modifier means exactly what?
For example:
public class Cat
int age;
int name;
static int count;
1) "static". (variable 'count'). This means:
this variable (or a static method) belongs only to its own class.
It doesn't belong to any object.
Other name: class-variable, class-method.
You can create objects from the class Cat, but the static 'count' variable is not the part of any cat-object!
2) "non-static": (age, name): these variables belongs only to the Cat-objects.
Other name: instance-variable, instance-method.
(instance means object!)
If you don't create any Cat-object, then these variables don't even exist!! If doesn't exist any Cat-object, then you can't use these variables. (The same applies to non-static methods too.)
No one can do anything with these variables (methods). Only the created objects can do something with them!
The nonstatic variables and methods are just a pattern for future objects.
The first existing thing is static: The JVM starts the program run with the STATIC main method.
This static main method (and all the other static method) can access/call/run only the static variables and static methods.
They can not access the non-static variables or non-static methods! The non-static variables and methods are accessable only by objects. After if you create an object in the static main method.
(Or, the static main method calls an other static method, and you will create an object inside this static method.)
Non-static (instance)methods/variables can use the static (class)variables/methods!
But static (class)methods/variables can not use the non-static variables/methods!
When the program use the class Cat at first time, the static count variable will be initialized to zero (zero is the default value.) The nonstatic (instance)variables (age,name) will be initialized only if you create a Cat-object!
It was some general explaining.
If you have questions, feel free to ask. (Via the 'Reply' button.)
+11
hidden #10625598
22 Mai 2020, 20:31
you are awesome, thanks
0
Sylwia
15 Juli 2020, 12:01
Thank you Gellert for your explanation!
0