+ 1

returning method with static and without static

https://code.sololearn.com/cYLsh8s9OWlY/?ref=app I have two methods. The first belongs to the class Num. This method don't need to be static. And the other method have to be static. Can someone explain why? Thank you.

22nd Jan 2019, 6:59 PM
Denise Roßberg
Denise Roßberg - avatar
4 Respostas
+ 6
In order for you to access the non-static method of class Num, you need to create an object then call the method. On the other hand, the static method runs without any instance of the class since it belongs to the class. Therefore, there’s no need to create an instance of the class to access it.  Check this out: https://medium.com/@gabriellamedas/differences-between-static-and-non-static-methods-in-java-b93156be75c6 https://stackoverflow.com/questions/3903537/what-is-the-difference-between-a-static-method-and-a-non-static-method
22nd Jan 2019, 7:41 PM
Lambda_Driver
Lambda_Driver - avatar
+ 4
You need the class name to access the static method Program.num(); remeber that static methods belong to the class and not the instance of class 😉 if you have a static method in the same class then you can just call it without the class name.
22nd Jan 2019, 7:37 PM
D_Stark
D_Stark - avatar
+ 2
D_Stark Lambda_Driver Thank you very much. Now it's clear.
22nd Jan 2019, 8:21 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
No problem, happy coding!
22nd Jan 2019, 8:22 PM
Lambda_Driver
Lambda_Driver - avatar