-1
class TheAnimal {

    public class Animal {
        void bark(){
            System.out.println("Woof-Woof");
        }

    }

    public static void main(String[] args){
         Animal dog = new Animal();
         dog.bark();
    }

}

// Keeps saying on line 12 Animal dog = new Animal(); after compiling that it's a non-static variable and that it cannot be referenced from a static context.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Camnaz
  • 11
  • 5

2 Answers2

0

You created an inner class Animal which can only be instantiated in a outer class instance context (which is probably not what you want/need now). Declare your inner class as static will let you instanciated it as you think:

class TheAnimal {   
    static public class Animal {
        void bark(){
            System.out.println("Woof-Woof");
        }   
    }

    public static void main(String[] args){
         Animal dog = new Animal();
         dog.bark();
    }   
}
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

You inner class Animal requires an instance of TheAnimal, make it static.

public static class Animal {
    void bark(){
        System.out.println("Woof-Woof");
    }
} 

Or, you need an instance of TheAnimal in main. Like,

public static void main(String[] args) {
    Animal dog = new TheAnimal().new Animal();
    dog.bark();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249