Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 637
EOG Avatar asked Mar 15 '26 02:03

EOG


1 Answers

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
like image 190
Jon Skeet Avatar answered Mar 17 '26 14:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!