1

How to access the anonymous inner class object in main method. It is giving compile time error saying that "cannot make static reference to non static method". If I am making anonymous inner class as static then I can access ut I want to access without making it static.

How to do that. Please help.

AnonymousInnerClass2.java

abstract class AnonymousInnerClass21
{
    abstract void m();  
}

public class AnonymousInnerClass2
{
    AnonymousInnerClass21 a=new AnonymousInnerClass21()
    {
        @Override
        void m() {
            System.out.println("Hello");
        }
    };

    public static void main(String[] args)
    {
        a.m();
    }
}
Community
  • 1
  • 1
Ankit
  • 95
  • 1
  • 9
  • Either declare `a` to be `static`, or create an instance of `AnonymousInnerClass2` in `main`. – k_ssb May 20 '18 at 04:32
  • Or, move the declaration of `a` inside `main` – k_ssb May 20 '18 at 04:34
  • `new AnonymousInnerClass2().a.m();` or better use a getter `new AnonymousInnerClass2().getA().m();` – c0der May 20 '18 at 04:52
  • THere is no class named AnonymousInnerClass2 in your code, only AnonymousInnerClass2**1*. And then, the question boils down to how to access a non static field from within a static method. Or the other way round: an anonymous class can't be accessed. You created an **instance** of that class, and that is about it. – GhostCat May 20 '18 at 05:08

1 Answers1

0

this is because for accessing inner class (whether its is normal/named class or Anonymous class), you must create object of class in which inner class is defined, you can try below

abstract class AnonymousInnerClass21
{
    abstract void m();  
}

public class AnonymousInnerClass2
{
    AnonymousInnerClass21 a=new AnonymousInnerClass21()
    {
        @Override
        void m() {
            System.out.println("Hello");
        }
    };

    public static void main(String[] args)
    {
        AnonymousInnerClass2 anonymousInnerClass2=  new AnonymousInnerClass2 ();//create outer class object
        anonymousInnerClass2.a.m(); // access inner class object through outer class object

    }
}
irfan
  • 878
  • 9
  • 10