-1

The code below gives a compile time error:non-static variable this cannot be referenced from a static context. Could someone tell me where I've made a mistake? I'm new to programming so it would be great if you explain it step by step.

import java.util.*;
public class Dog{
int age;
String name;
public void BowBow(){
    System.out.println("Bow Bow I'm Dog1");
}
public  class Dog1 extends Dog{
    int age1;
    String name1;
    public void owow(){
        System.out.println("oow oow I'm Dog2");
    }
}
public class Dog2 extends Dog1{
    int age2;
    String name2;
    public void uhh(){
        System.out.println("uhh uhh I'm Dog3");
    }
}
public static void main(String [] args){
        Dog1 obj1 = new Dog1();
        Dog2 obj2 = new Dog2();
        Dog2 obj3 = new Dog2();
        obj1.age = 18;
        obj1.name = "Hugo";
        System.out.println("age:"+obj1.age);
        System.out.println("Name:"+obj1.name);
        obj2.age1 = 19;
        obj2.name1 = "Huxley";
        System.out.println("Age:"+obj2.age1);
        System.out.println("Name:"+obj2.name1);
        obj3.BowBow();
        obj3.owow();
        obj3.uhh();

  }
}   
Ayush
  • 1,510
  • 11
  • 27
  • I don't see `this` used anywhere – user Jun 30 '20 at 15:01
  • But i get this error when i compile this code – Love Heals Jun 30 '20 at 15:10
  • You're trying to refer to a non-static nested class from a static method. I doubt that nested classes are what you were trying to get, so you should probably move `Dog1`, etc. out of the `Dog` class – user Jun 30 '20 at 15:12

1 Answers1

1

The problem lies in the fact that the Dog1, Dog2 classes are non-static nested(inner) classes, and a non-static nested class in Java contains an implicit reference to an instance of the parent class. So to instantiate Dog1, you would need to instantiate Dog as well.
However, if you make Dog1 a static class or perhaps even an outer class, then it will not need a reference to Dog and you would then be able to instantiate it directly in the static main method.


So you've got 3 options:

1)Make Dog1, Dog2 static inner classes, and then your code will run fine.

2)Make Dog1, Dog2 outer classes

3)Create the inner object within the outer object, in this manner:

Dog1 obj1 = new Dog().new Dog1();

Ayush
  • 1,510
  • 11
  • 27