+ 1
Does it matter if I write: private static void... OR public static void...?
Look at title ^
15 Réponses
+ 1
yahel I'm just talking about the main method which has to be 'public static void'. You can have other methods in the class with different method signature similar to what you have mentioned.
They are not much useful since private cannot be inherited and static methods are hidden in the extended classes.
+ 7
yahel I imagine private static methods could be a shared method designed to maintain state or coordinate some action across all instances of a class.
Making it private will narrow its scope and usage to the specific class for which the method exists.
For this reason, such usage would be at risk of possibly following any number of anti-patterns that should be reviewed and avoided.
Still yet, I'm sure there are also valid usage scenarios as well. It's really something that would be assessed on a case by case basis.
+ 5
yahel Here is a silly / simple example of a scenario using the private static members.
https://code.sololearn.com/cEDO76cAZJ9F/
+ 3
Yes it is possible. Here is a small example for you to understand it better.
https://code.sololearn.com/c1iWfL13Gtf6/?ref=app
+ 2
'private static void' will not work because it limits the visibility of the method and the JVM will not be able to locate it. The JVM makes a call to the main method from outside the class or package or the project so the method has to be strictly 'public'.
0
Avinesh so I don't need to use it anywhere right? Because I saw some codes that used "private"... why do they need to use it? They can just use "public" right?
0
Avinesh and I have another question. When I write a method, can I just write: "static void hello(){}" OR just write "void hello(){}" ?
0
Avinesh ok thanks. And can you answer the other thing that I asked please? :
and I have another question. When I write a method, can I just write: "static void hello(){}" OR just write "void hello(){}" ?
0
yahel I would recommend you to read about the static keyword. Static methods can be invoked without creating an instance of the class it is declared in. So it's completely upto you to decide.
0
Avinesh Ok. But is it possible to make a method that is built just from a void? Like this: void hello(){
}
0
Avinesh THANK YOU VERY MUCH! FINALLY I UNDERSTAND THIS THING
0
David Carroll thanks for the information!
0
David Carroll do you have an example with the private statement?
0
Public keyword means that any function can access that method. Private means that everything in the same class can access it, but other classes can’t access it.
0
No english