0

i cant create a Dog object, i should be able to i dont understand the compiling error, non-static variable this cannot be referenced from a static context

public class Program
{

abstract class Animal{
    private String name;
    String latin;
}

abstract class Carnivore extends Animal{}
abstract class Herbivore extends Animal{}

interface Petable{
    public void pet();
}

class Dog extends Carnivore implements Petable{
    public void pet(){System.out.println("bark");}
}


public static void main(String[] args) {
    Dog d = new Dog();
    d.pet();
}
}
  • 7
    All your classes are nested inside the `Program` class. Your classes are so-called *non-static inner classes*. These cannot be created without an instance of the enclosing class (`Program` in your case). You have three options: you need to either move your classes to the top level, so they are no longer nested, *or* change your classes to `static`, *or* create an instance of the enclosing class (`Dog d = new Program().new Dog()`). – MC Emperor Jun 17 '19 at 11:56

2 Answers2

1

You need to move the inner classes outside of the Program class, otherwise they have to be instantiated with new Program().new Dog();

public class Program {

   public static void main(String[] args) {
      Dog d = new Dog();
      d.pet();
   }
}

abstract class Animal{
    private String name;
    String latin;
}

class Dog extends Carnivore implements Petable{
    public void pet() {
       System.out.println("bark");
    }
}

abstract class Carnivore extends Animal{}
abstract class Herbivore extends Animal{}

interface Petable{
    public void pet();
}

Thanks to @Blokje5 and @MC Emperor for references and nested instance class instantiation syntax, go upvote them.

Austin Schaefer
  • 695
  • 5
  • 19
0

Your nested classes are not static, they belong only to members of the class. To fix this, add static to your class declarations.

abstract class Animal{
    private String name;
    String latin;
}

change to

abstract static class Animal{
    private String name;
    String latin;
}

Now you can use them without initializing a member of the class.