1

error on this code while running getting error-:non-static variable this cannot be referenced from a static context What should i do to resolve this code

class Testy {
    void girl()
    {
        System.out.println("Black girl");

    }

    class Testy1 extends Testy
    {
        void girl()
        {
            System.out.println("White girl");

        }
    }

    public static void main(String[] args) {
        Testy p=new Testy1 ();
        p.girl();
    }

}
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
  • 5
    Possible duplicate of [Non-static variable cannot be referenced from a static context](http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – Mickael Jan 17 '17 at 10:46
  • The problem is that `Testy1` is an inner class to `Testy` and not `static`. Thus, `Testy1` needs an instance of `Testy` on creation, which is not available in `main`. Inner classes are an somewhat advanced concept, so i suggest you put each class in its own source file to get started – Gyro Gearless Jan 17 '17 at 10:50
  • Nice test example – johnny 5 Jan 17 '17 at 15:04

2 Answers2

0

Here is the correct code.

Make your Testy1 class static as it is a inner class.

  class Testy {
void girl()
{
    System.out.println("Black girl");

}

static class Testy1 extends Testy
{
    void girl()
    {
        System.out.println("White girl");

    }
}

public static void main(String[] args) {
    Testy p=new Testy1();
    p.girl();
}

}
Doctor Who
  • 747
  • 1
  • 5
  • 28
0

If you want to use inner class then you have to call function as follows

   class Testy {
        void girl()
        {
            System.out.println("Black girl");

        }


        class Testy1 extends Testy
        {
            void girl()
            {
                System.out.println("White girl");

            }
        }


    public static void main(String[] args) {
        Testy t = new Testy(); // first create object of outer class
        Testy.Testy1 t1 = t.new Testy1(); //using t create object of inner class
        t1.girl();
    }
}
js_248
  • 2,032
  • 4
  • 27
  • 38