Why (static,void) dose not allowed befor main class Myname | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why (static,void) dose not allowed befor main class Myname

public class Animal { static void bark() { System.out.println("Woof-Woof"); } } static class MyName { public static void main(String[ ] args) { Animal dog = new Animal(); dog.bark(); } }

3rd Nov 2016, 7:47 PM
sami hamza
sami hamza - avatar
1 Answer
+ 2
Simply because static methods must be used with class name. You don't need to create an instance of Animal to use the bark method. A static method can be used with: MyClassName.myStaticMethod(), without instance of MyClassName. In your case, to use the bark method, you must do: Animal.bark(). Or if you want to use an instance (dog, in your case), only remove the static keyword of the bark method, and replace it by "public" :)
3rd Nov 2016, 8:59 PM
Volts
Volts - avatar