Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to explicitly specify a constructor in Java?

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?

like image 479
merlin2011 Avatar asked Feb 05 '14 02:02

merlin2011


People also ask

How do you declare an explicit constructor in Java?

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.

How do you reference a constructor in Java?

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.

Can we call constructor implicitly?

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.

Can we define constructor as protected?

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.


1 Answers

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.

like image 184
Hovercraft Full Of Eels Avatar answered Sep 22 '22 02:09

Hovercraft Full Of Eels