how to generate constructors in eclipse

删除回忆录丶 提交于 2019-12-10 01:50:32

问题


I have a class A and B.M extends A. Now I want a create a constructor of B using code generation option of eclipse which accepts parameters and set values of all fields of B (I mean it should also set fields inherited from A).

Is there any shortcut to generate such code in eclipse?


回答1:


Right click in the editor and click "Source -> Generate Constructor using Fields". You can select the super constructor to use and also select instance variables to add to the constructor.




回答2:


Eclipse (3.5) has no built in option for that particular case, but I would anyway suggest that you have a separate constructor in the super class, which the sub-class invokes through super(...) in its constructor.

This would be easier to maintain. If you for instance add a filed in the super class, you would need to remember to update the sub-class as well.

class A {
    int i;
    public A(int i) { this.i = i; }
}

class B extends A {
    int j;
    public B(int i, int j) {
        super(i);
        this.j = j;
    }
}



回答3:


There is no automatic way to do it and I'm close to believe that the eclipse team did this on purpose as it would lead to bad design.

Constructing a class is about initializing the objects own fields only. If you need to set (init) fields on the superclass, call the superclasses constructor, if you need to change superclass fields, call the superclasses getter and setter methods.

To me it's bad design to init superclass fields and can be avoided easily.



来源:https://stackoverflow.com/questions/3484867/how-to-generate-constructors-in-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!