Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous class, Inheritance, and overriding

public class A {
    public A() {
        foo();
    }

    private void foo() {
        System.out.print("A::foo ");
        goo();
    }

    public void goo() {
        System.out.print("A::goo ");
    }
}

public class B extends A {
public B() {
    foo();
}

public void foo() {
    System.out.print("B::foo ");
}

public void goo() {
    System.out.print("B::goo ");
}

    public static void main(String[] args) {

A b = new B() {
        public void foo() {System.out.print("Anonymous::foo ");}
        public void goo() {((B)this).foo();}
        };

}
}

I'd like your help with understanding why does the program print A::foo Anonymous::foo Anonymous::foo. Is this anonymous class replace the former B? overrides its methods?

As I see it, it should go to A's default constructor, run A's foo- print "A::foo", than run B's goo, since it was properly overrided, but now B's goo is the one in the Anonymous class, so it casts this to B (Which does nothing), and run its foo, which is the foo above, of B, so it should print "Anonymous:foo". What do I get wrong?

Thanks a lot.

like image 944
Numerator Avatar asked Dec 17 '22 09:12

Numerator


2 Answers

Your question isn't all that clear, but let me just say that the the answer would be exactly the same if instead of an anonymous class extending B, you had a top-level class C extending B. Nothing about anonymous classes makes them behave differently with respect to polymorphism and inheritance. When B's constructor calls foo(), the overriding version in the most-derived class -- here the anonymous class -- is invoked.

like image 63
Ernest Friedman-Hill Avatar answered Jan 04 '23 23:01

Ernest Friedman-Hill


I think the confusing thing here is you have two foo methods. One is private so it's not eligible for overriding, the other is public so it can be overridden. B is calling foo in its constructor but that's overridden by its subclass.

like image 42
Nathan Hughes Avatar answered Jan 04 '23 22:01

Nathan Hughes