There is an abstract class:

public abstract class Drink { public void taste(){ System.out.println("Вкусно"); } } 

In theory, it is forbidden to create copies of it, but the IDE helped circumvent this prohibition in the following way:

 public static Drink getDeliciousDrink() { return new Drink() { @Override public void taste() { super.taste(); } }; } 

What happens when overriding the taste function and why can I create an instance of this class?

    1 answer 1

    You do not create an instance of the Drink class. Design

     new Drink() { @Override public void taste() { super.taste(); } } 

    Defines an anonymous subclass of the Drink class with the overridden taste method and creates an instance of this subclass. Because the base class is only declared abstract, but does not contain abstract methods, then its heirs can be created. Moreover, since in this subclass, only one method is redefined, which, in fact, simply calls the parent method, then you can write

     public static Drink getDeliciousDrink() { return new Drink(){}; } 
    • Clearly, I somehow did not reach even the study of anonymous classes.) There is also a construction when an interface class object is created, but it receives a reference to the real List object <> a = new ArrayList <> (); - Alexander