本文介绍了在抽象类的构造函数中使用抽象的init()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有这样的事情: 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)); // .... } } //代码中的某处菜单menu1 = new ConcreteMenu(); 正如您所见,超类的init方法是抽象的,并且在创建对象后由构造函数自动调用。 / p> 我很好奇我是否可以遇到类似这样的代码的某些问题,当我需要创建一些这样的结构时,其结构不会被改变时间。 会有更好的方法吗?它适用于Java,但是它可以在C ++和ActionScript中使用吗? 感谢您的回答。解决方案不要从构造函数中发现过多的方法。 来自 Effective Java 2nd Edition的引用,第17项:设计和继承文档,或者禁止它:这是一个示例来说明: 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); } } 新孩子(42); //打印0} } 这里,当 Base 构造函数调用 overrideMe , Child 尚未完成初始化 final int x ,该方法获取错误的值。这几乎肯定会导致错误和错误。 相关问题 从父类构造函数调用重写方法 基类构造函数在Java中调用重写方法时的派生类对象的状态 另请参阅 FindBugs - 未初始化的阅读从超类的构造函数调用的字段方法 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 codeMenu menu1 = new ConcreteMenu();As you can see superclass's init method is abstract and is called by constructor automatically after object is created.I'm curious if i can run into some sort of problems with code like this, when i need to create some object of this kind whose structure wont't be changed in time.Would be any approach better? It works in Java, but will it work in C++ and possibly ActionScript?Thank you for answer. 解决方案 DO NOT INVOKE OVERRIDEABLE METHODS FROM THE CONSTRUCTOR.A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:Here's an example to illustrate: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 Base constructor calls overrideMe, Child has not finished initializing the final int x, and the method gets the wrong value. This will almost certainly lead to bugs and errors.Related questionsCalling an Overridden Method from a Parent-Class ConstructorState of Derived class object when Base class constructor calls overridden method in JavaSee alsoFindBugs - Uninitialized read of field method called from constructor of superclass 这篇关于在抽象类的构造函数中使用抽象的init()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-18 14:47