Frage

I know this works:

class Main{
    public static void main(String[]args){
        AbstractClass object = new AbstractClass(){ ... };
    }
}

It creates an object with implicitly extends the AbstractClass class (Which is obviously abstract).

But will the following work too?

class Main{
    public static void main(String[]args){
        ConcreteClass object = new ConcreteClass (){ ... };
    }
}

ConcreteClass being a class which isn't abstract.

War es hilfreich?

Lösung

Most certainly, this would work: the class that you extend into an anonymous class does not need to be abstract - it could be any non-final class, or even an interface (in which case you would need to implement all its methods).

Moreover, when the class is non-abstract, you could subclass without overriding any of its methods. This feature was used in the so-called type-safe enum pattern, which has been common prior to introduction of enum classes into Java.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top