Why does it work to call method4 without being static?
Why can Method4 be called being not static?
In der Diskussion
Du musst angemeldet sein, um einen Kommentar schreiben zu können
19 April, 14:14
Just like non-static fields can be used to set the values of other non-static fields (see my explanation on your other post) non-static methods can call other non static methods. Some explanations: Fields are executed when they are created (static fields are created when a class is loaded into memory, non-static fields are created when an object is created and are unique to only that object). Methods are executed when they are called. Static methods can be called without any objects, and non-static methods require an object to be created and used to call them. Static methods exist before any object is created. This means that they can access any other static method or field, however the non-static methods and fields do not exist and therefore can not simply be accessed. Because they are executed when called, you can create an object inside a static method and then use that object to access that object's fields and methods. In this code you can see that the static method2() creates a new Solution object which is then used to call the non static method3(). This is legal because an object was created and that object contained the method3() that was accessed.
19 April, 15:26
I understood that about method3() because it was called with the object new Solution().methode3, but method4 is simply called as a static method in method3 by typing method4(). I thought this was only possible with static methods. I expected it to be necessary at least to have this.method4()... @Guadalupe Gagnon, this is only possible in between the same class(file), right? If we were to call the method from another class (not nested or not inbetween the same class file) we would need to call the method by objectname.method, right?
19 April, 16:06
I expected it to be necessary at least to have this.method4() That actually is a really good observation. method3(), which calls method4(), is not a static method. Therefore, logically, to call method3() you MUST have an object call it. Because it is impossible to call that method without an object this means an object MUST exist if method3() is called. Since an object is guaranteed to exist for method3() to be called the compiler literally uses that same object to call method4(), which in code is the keyword this. Java it doesn't require you to use the this keyword as it is implied, however it is not illegal to do so. So, in method3(), this.method4() is the same as just simply method4(). This same rule is applied for any method called within another method.