Java - Do java have something like C#'s struct automatic constructor

你说的曾经没有我的故事 提交于 2019-12-24 01:14:35

问题


I've been using C# for a long time and now I need to do something in Java.

Is there something like C#'s struct automatic constructor in java ?

What I mean is In C#

struct MyStruct
{
    public int i;
}
class Program
{
    void SomeMethod()
    {
        MyStruct mStruct; // Automatic constructor was invoked; This line is same as MyStruct mStruct = new MyStruct();
        mStruct.i = 5;   // mStruct is not null and can i can be assigned
    }
}

Is it possible to force java to use default constructor on declaration ?


回答1:


No - Java doesn't support custom value types at all, and constructors are always explicitly called.

However, your understanding of C# is incorrect anyway. From your original post:

// Automatic constructor was invoked
// This line is same as MyStruct mStruct = new MyStruct();
MyStruct mStruct; 

That's not true. You can write to mStruct.i without any explicit initialization here, but you can't read from it unless the compiler knows everything has been assigned a value:

MyStruct x1; 
Console.WriteLine(x1.i); // Error: CS0170: Use of possibly unassigned field 'i'

MyStruct x1 = new MyStruct();
Console.WriteLine(x1.i); // No error



回答2:


No, you always need to explicitly call a constructor in Java.

Since there may be multiple constructors, calling a specific constructor explicitly would probably be good practice anyway.




回答3:


Java doesn't support the Struct keyword (see: http://msdn.microsoft.com/en-us/library/ms228600(v=VS.90).aspx) so you would be needing to use a Class with only public objects (and no functions.) You always need to initialise classes.



来源:https://stackoverflow.com/questions/11701662/java-do-java-have-something-like-cs-struct-automatic-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!