If abstract classes and interfaces cannot be instantiated, what is happening here?

Asked

Viewed 128 times

9

I discovered that interfaces and abstract classes cannot be instantiated, but my teacher gave me an example that left me in doubt, because it seems very an instance of interface ActionListener.

Follows the code:

ActionListener tarefa = (new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        HORAS();
    }
});

2 answers

7


They alone cannot be instantiated, but this is not a blind rule that has been created, there is a reason: it cannot because the interface does not have an implementation and therefore could not be executed, but what if you can have this implementation? , Why not allow?

What is doing there is something called an anonymous class implementation, so there is what to execute and then you can instantiate the class you just created, even if the type is still the most general, ie the type of the interface. So you’re instantiating a class that’s just been created and can only be used there since it doesn’t even have a name.

  • Thank you so much for the explanation! I will study more about anonymity implementation of classes. New concept. Thank you so much!

6

Despite new ActionListener() seems to indicate that it is instantiating the interface, what is being done is to declare and at the same time implement and instantiate a class that implements that interface.

This expression declares what is called Anonymous Classes.

Anonymous classes are like local classes but no name, both are inner classes.

An anonymous class can be an implementation of an interface or a class inherited from another.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.