How to reduce the repetitiveness and bloat of Java constructors?
I'd like to avoid the repetitious code-bloat and typing tedium of defining "C-struct-like" classes like:
class Foo {
int x;
float y;
String z;
public Foo(int x, float y, String z) {
this.x = x;
this.y = y;
this.z = z;
}
}
? E.g. are there any Eclipse tricks that may be helpful here?
To see what I mean by "code-bloat", compare the above with what it takes to define the corresponding struct in C:
struct f开发者_开发知识库oo {
int x;
float y;
char *z;
}
Each member field is mentioned only once, whereas in the Java code it needs to be mentioned three times (one of them in the form of the corresponding constructor argument).
In eclipse you can right click in java editor, source -> generate constructors using fields. I guess that is what you are looking for.
Eclipse has a "Generate Constructor using Fields..." in the Source menu.
You can do that in Java as well, but it is against the basic OOP principles:
class Foo {
public int x;
public float y;
public String z;
}
some other class:
Foo foo = new Foo();
foo.x = 1;
// etc..
Just like C
s struct:
struct Foo {
int x;
float y;
char *z;
};
struct Foo foo;
foo.x = 1;
// etc...
No way around that in Java, unfortunately, if you want to initialize those values in the constructor. Scala has a solution for it if you're open to another JVM language...
EDIT: You could just make all your fields public tho. In theory, this is a bad idea. In practice, sometimes it's the right solution.
精彩评论