The answer to this question explains the cause for the ambiguous constructor problem, but if I actually want to construct a third-party object which contains such constructors, and I want to pass the argument to be null
, can I construct the object anyways by somehow telling java which constructor I mean?
In particular, in this example:
public Example(String name) {
this.name = name;
}
public Example(SomeOther other) {
this.other = other;
}
Suppose I want to actually construct a new Example(null)
using the first constructor.
Is there some syntax that will allow me to do this?
Explicit use of the this() or super() keywords allows you to call a non-default constructor. To call a non-args default constructor or an overloaded constructor from within the same class, use the this() keyword. To call a non-default superclass constructor from a subclass, use the super() keyword.
A constructor reference can be created using the class name and a new keyword. The constructor reference can be assigned to any functional interface reference that defines a method compatible with the constructor.
The constructors can be called explicitly or implicitly. The method of calling the constructor implicitly is also called the shorthand method. Example e = Example(0, 50); // Explicit call. Example e2(0, 50); // Implicit call.
A protected constructor means that only derived members can construct instances of the class (and derived instances) using that constructor. This sounds a bit chicken-and-egg, but is sometimes useful when implementing class factories. Technically, this applies only if ALL ctors are protected.
Yes, by explicitly casting the null argument: i.e., by calling Example((String)null);
or Example((SomeOther) null);
And as mentioned, doing this suggests a bad design, and I agree. You will want to try to write bullet-proof code where this sort of ambiguity isn't possible or doesn't matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With