Search code examples
javainheritanceanonymous-class

Why anonymous class can't access private methods and variables?


package demo;

class Child{
    private static int a=50;
    public void fin() {
        System.out.println("hello");
    }
    private void fly() {
        System.out.println("lol");
    }
}

public class Hello {
    public static void main(String[] args) 
    {  
        Child c=new Child() {

            public void f() {
                System.out.println("sorry"+a);
            }
            public void fin() {
                System.out.println("hello");

            }

        };
        c.fin();

}}

Above is the code of java my point is why cant private methods and variables be called in anonymous class as I had read somewhere that an anonymous class can access all members of enclosed class.
https://www.baeldung.com/java-anonymous-classes go checkout which specifies that each member of the anonymous class can access all members of the enclosed class.


Solution

  • There is a confusion in that code about "inner class" and "anonymous class".

    Notice you have 3 classes there:

    • Child
    • Hello
    • Hello$1: An anonymous class declared inside of Hello and whose parent is Child

    The confusion in the code is about the latter:

    • Hello$1 is a subclass of Child
    • Hello$1 is an inner class of Hello

    This means:

    • Hello$1 cannot access private fields from Child, as subclasses cannot access private elements of their super classes
    • Hello$1 can access private fields from Hello, as anonymous inner classes can access private elements of their enclosing classes

    Check it more clearly in this code:

    class Child {
        private int a = 50;
    }
    
    public class Hello {
        private int b = 60;
    
        public void f() 
        {  
            Child c = new Child() {
                public void f() {
                    // System.out.println("a = " + a); // This won't compile
                    System.out.println("b = " + b); // This compiles OK
                }
            };
        }
    }