+ 1

why this code is not running without "static" word?

when there are two class and I am using object this code is running without word static before void, but when I edit it and use just one class it didn't run without "static" before void. And why this is happening explain please ☺ original code : https://www.sololearn.com/learn/Java/2155/ Edited code : public class Animal { static void bark() { System.out.println("Woof-Woof"); } public static void main(String[ ] args) { bark(); } }

26th May 2018, 12:03 PM
RH Tasin
RH Tasin - avatar
2 Respostas
+ 10
If u don't write static then u need to create an object of it! but with static u don't. That's why, ur code is not running because u have removed static but not created an object. Hope this helps!!!
26th May 2018, 12:36 PM
Mayank Rampuriya
Mayank Rampuriya - avatar
+ 9
static methods belong to the class and not the instance of it so without static you would have to call it using Animal x = new Animal(); x.bark() and with static you would call the class method like so Animal.bark(); Like Mayank Rampuriya said you do not need to create a instance of it if its static
26th May 2018, 12:52 PM
D_Stark
D_Stark - avatar