开发者

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 constr开发者_JAVA百科uctor 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.


No. Java doesn't have implicit constructors.


No, you need to construct it explicitely:

 DoSomethingWithAFoo(new Foo(s));     
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜