The problem occurs when you try to do this:
public class Dog { public static void main(String args[]){ bark(); // ERROR: non-static method cannot be referenced // from a static context } void bark() { System.out.println("Woof"); } }
Java is telling us that you cannot call bark() if you haven’t got a dog!
The solution is to instantiate a Dog before you call the bark() method, or… and this is the really lazy method… just declare your bark() method static, so that it doesn’t need an instance.
Solution 1: Two classes
public class DogMain { public static void main(String args[]){ Dog d = new Dog(); d.bark(); } } class Dog { void bark() { System.out.println("Woof"); } }
Solution 2: Self-instantiating class
public class Dog { public static void main(String args[]){ Dog d = new Dog(); d.bark(); } void bark() { System.out.println("Woof"); } }
Solution 3: Lazy cop-out
public class Dog { public static void main(String args[]){ bark(); } static void bark() { System.out.println("Woof"); } }