Anonymous class not allowing extra method (that is not implemented in superclass) in java

piny :

In a java tutorial (https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html) I read that in a anonymous class you can create a method not implemented in the superclass. But I tried the following and it doesn't work:

class Superclass {
}

class Anonymous {
    public void start() {
        Superclass obj = new Superclass() {
            public void myMethod() {
                System.out.println("hello world");
            }
        };

        obj.myMethod();
    }
}

class Main {
    public static void main(String[] args) {
        Anonymous obj = new Anonymous();
        obj.start();
    }
}

If possible can anyone explain what I have done wrong, thanks for time.

Andreas :

You can create a new method in the anonymous class, but since code outside the anonymous class can't even know about the method, you cannot call it from outside.

You can however call it from inside.

abstract class Superclass {
    public abstract void doStuff();
}

class Anonymous {
    public void start() {
        Superclass obj = new Superclass() {
            @Override
            public void doStuff() {
                myMethod();
            }
            public void myMethod() {
                System.out.println("hello world");
            }
        };

        obj.doStuff(); // prints: hello world
    }
}

To explain further, an anonymous class is like an unnamed local class.

public void start() {
    class $1 extends Superclass {
        @Override
        public void doStuff() {
            myMethod();
        }
        public void myMethod() {
            System.out.println("hello world");
        }
    };
    Superclass obj = new $1();

    obj.doStuff(); // prints: hello world
}

As you can see, since obj is a Superclass, not a $1, you cannot call myMethod(), and you cannot declare obj to be a $1 class, because when it is anonymous, it doesn't have a name1.

1) Internally, anonymous classes have names, e.g. something like Anonymous$1, i.e. the name of the outer class, a dollar sign, and a number. You can see those names in the compiler-generated .class files. But you can't write code with those names.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=396690&siteId=1