Java – use the abstract init() function in the constructor of the abstract class

I have something like this:

public abstract class Menu {
     public Menu() {
      init();
     }

     protected abstract void init();

     protected void addMenuItem(MenuItem menuItem) {
      // some code...
     }
    }

    public class ConcreteMenu extends Menu {
     protected void init() {
      addMenuItem(new MenuItem("ITEM1"));
      addMenuItem(new MenuItem("ITEM2"));
      // ....
     }
    }

//Somewhere in code
Menu menu1 = new ConcreteMenu();

As you can see, the init method of the superclass is abstract and is automatically called by the constructor after the object is created

I am curious that if I can encounter some problems with such code, when I need to create some such objects, their structure will not change in time

Is there a better way? It works in Java, but can it work in C and ActionScript?

Thank you for your answer

Solution

Don't send too many methods to the constructor

Valid java version 2, item 17: references to inherited designs and documents, otherwise it is prohibited:

The following is an example:

public class ConstructorCallsOverride {
    public static void main(String[] args) {
        abstract class Base {
            Base() { overrideMe(); }
            abstract void overrideMe(); 
        }
        class Child extends Base {
            final int x;
            Child(int x) { this.x = x; }
            @Override void overrideMe() {
                System.out.println(x);
            }
        }
        new Child(42); // prints "0"
    }
}

Here, when the base constructor calls overrideme, child has not finished initializing the final int x, and the method obtains the wrong value This almost certainly leads to mistakes and mistakes

Related issues

> Calling an Overridden Method from a Parent-Class Constructor > State of Derived class object when Base class constructor calls overridden method in Java

You can also have a look

> FindBugs – Uninitialized read of field method called from constructor of superclass

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>