eclipse 如何在eclipse中生成构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3484867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 15:00:09  来源:igfitidea点击:

how to generate constructors in eclipse

javaeclipsecode-generation

提问by akshay

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).

我有一个类 A 和 BM 扩展 A。现在我想使用 eclipse 的代码生成选项创建一个 B 的构造函数,它接受参数并设置 B 的所有字段的值(我的意思是它还应该设置从 A 继承的字段)。

Is there any shortcut to generate such code in eclipse?

在eclipse中生成这样的代码有什么捷径吗?

回答by kylc

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.

在编辑器中右键单击并单击“Source -> Generate Constructor using Fields”。您可以选择要使用的超级构造函数,也可以选择要添加到构造函数的实例变量。

回答by aioobe

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.

Eclipse (3.5) 没有针对这种特殊情况的内置选项,但我还是建议您在 super class 中有一个单独的构造函数,子类super(...)在其构造函数中调用它。

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;
    }
}

回答by Andreas Dolk

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.

没有自动的方法来做到这一点,我几乎相信 eclipse 团队是故意这样做的,因为它会导致糟糕的设计。

Constructing a class is about initializing the objects ownfields 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.

构造一个类只是初始化对象自己的字段。如果需要在超类上设置(init)字段,调用超类的构造函数,如果需要改变超类的字段,调用超类的getter和setter方法。

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

对我来说,初始化超类字段是一种糟糕的设计,可以轻松避免。