Java override method - (anonymous subclass) when building an instance of an object

I support Java 8 code that looks like this:

Class Entity  {
   protected Model theModel;

   public Entity()  {
       init();
   }

   protected void init()  {
       this.theModel = new Model();
   }
}

Class Model  {
}

Class SubModel extends Model {
}

main {
    Entity newEntity = new Entity()  {
        @Override
        protected void init()  {
            this.theModel = new SubModel();
        }
    };
}

Currently, the code compiles and runs correctly, but now I need to update it.

My question is:

  • How does method overriding init()work in general newEntity?
  • What is the correct terminology for this method override included in the object constructor statement?

My research so far shows that Java cannot dynamically redefine methods - overriding cannot be performed on this basis, since method overrides do not belong to a class for every object. But this piece of code seems to show that Java can do this in practice?

+6
2

, , , .

, ( ), , , , init(), , , init , SubModel.

Java " 17: " :

" , , . , . , . , . , , , . , , :"

, :

" , overrideMe, Super :

public class Super {
    // Broken - constructor invokes an overridable method
    public Super() {
        overrideMe();
    }

    public void overrideMe() {
    }
}

public final class Sub extends Super {
    private final Date date; // Blank final, set by constructor

    Sub() {
        date = new Date();
    }

    // Overriding method invoked by superclass constructor
    @Override public void overrideMe() {
        System.out.println(date);
    }

    public static void main(String[] args) {
        Sub sub = new Sub();
        sub.overrideMe();
    }
}

" , , null , overrideMe Super Sub . , ! , overrideMe date, NullPointerException, Super overrideMe. , NullPointerException println ."

, , , : , , , . , , .

, , , , , , , , , , . , - , , , , , , , - , .

+6

, , , , , , , .

, , , , . , , , , .

, , .

, IDE, . , , , , , , , .

, : .

- . , , .

"" , , , . . , . , , this () , . , overridable, .

++, , , , ( , ), , ++, - .

+5

Source: https://habr.com/ru/post/1017114/


All Articles