+ 2

What does static method do for a class?

5th Nov 2018, 12:57 PM
Alquen
Alquen - avatar
4 Réponses
+ 5
It can be called easily as it does not need any objects to invoke. class Aa{ static void hi(){ System.out.print("hello"); } public static void main (String[] args){ hi(); //output: hello } } You can call hi() directly in main() method without creating instance of the class
5th Nov 2018, 1:13 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 1
Thanks Muhd Khairul Amirin Bin Yaacob. But can I know its purpose why we use static method even though we can just create instance.
5th Nov 2018, 3:09 PM
Alquen
Alquen - avatar
0
you assign a method as static when you want to use it in another class or quick calling of it. for example suppose you take a method: void m() {} when you want to call it you need to create the object of the class but if you use static before void you can call it directly as: m(); hope you get it.
7th Nov 2018, 3:10 AM
Vivek Mishra
Vivek Mishra - avatar