Andrew Shelansky
Andrew Shelansky

Reputation: 5052

Can I create a non-explicit constructor for a Java class?

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

Answers (2)

Thierry Roy
Thierry Roy

Reputation: 8512

No, you need to construct it explicitely:

 DoSomethingWithAFoo(new Foo(s));     

Upvotes: 0

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143144

No. Java doesn't have implicit constructors.

Upvotes: 1

Related Questions