I guess what I'd want is simply not possible, but I want to make sure. Say I have
public class bar {
public bar() {
}
public bar(Object stuff) {
// something done with stuff.
}
}
and an extension
public class foobar extends bar {
public foobar() {
super();
// some additional foobar logic here.
}
public foobar(Object stuff) {
// Do both the
// "some additional foobar logic" and
// "something done with stuff" here.
}
}
How can I make the foobar(Object stuff) as simple as possible while also avoiding to duplicate code? I can't simply call super(stuff) as then "some additional foobar logic" isn't done, and I can't call just this() as then I don't do what I'd want to do with "stuff".
NOTE : I realized I don't actually need to do this in this case, so this is now here only for theoretical purposes.
You can only chain to one constructor. Typically the best approach is for the "less specific" constructors (the ones with fewer parameters) to chain to the "more specific" ones, with a single "master" constructor which is the only one with logic in:
public class FooBar extends Bar {
public FooBar() {
this(null); // Or whatever value you want for "stuff"
}
public FooBar(Object stuff) {
super(stuff);
// Initialization logic
}
}
See more on this question at Stackoverflow