views:

73

answers:

3

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?

+2  A: 

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;
    }
}
aioobe
+1  A: 

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.

kyl
But it will not generate initialization for public/protected members of the super class, which I suppose is what the OP is after.
aioobe
@aioobe - agree, that was the main poinr of akshays question.
Andreas_D
A: 

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.

Andreas_D