Reputation: 5052
By default, C++ will do "auto promotion" in assignment if appropriate constructors exist (and are not declared explicit
).
In Java, this behavior doesn't happen by default. If I want automatic promotion, is there a way to declare my constructors as implicit?
For example, here is some C++ code that has the effect that I want:
class Foo {
public:
Foo(string) { /* ... */ }
/* Foo's methods and stuff */
};
void DoSomethingWithAFoo(Foo foo)
{
/* ... */
}
int main()
{
string s = "I am a happy string, I swear!";
DoSomethingWithAFoo(s);
return 0;
}
Generally, in C++ this is allowed, and the string s
will be automatically promoted (by constructing a temporary Foo
from s
).
Since the Foo(string)
constructor is not marked explicit, I don't even need a typecast.
Is there a way to do this in Java?
I ask because I am trying to create a specific type that represents any one of a specific variety of other types. For example, imagine a class Primitive
that was representing either a single boolean, integer, character, or double (that's not my specific example, but it is related).
Methods in my system that expect a Primitive should also accept any of the "real types" that the Primitive might represent (by auto-promotion to an anonymous object of type Primitive through a constructor call).
In my actual work (as opposed to this example), my equivalent to the Primitive
class has constructors both from a few primitive types as well as several object types (each constructor taking only the one parameter). Ideally I would want auto promotion for all of them.
Upvotes: 0
Views: 152
Reputation: 8512
No, you need to construct it explicitely:
DoSomethingWithAFoo(new Foo(s));
Upvotes: 0