Java - Java有类似于C#结构体自动构造函数的功能吗?

3

我已经使用C#很长时间了,现在我需要在Java中做一些事情。

Java中是否有类似于C#结构体自动构造函数的东西?

我的意思是,在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
    }
}

是否可能在声明时强制Java使用默认构造函数?


直接调用构造函数有什么问题? - Qnan
C# 不会自动调用结构体的默认构造函数。 - CodesInChaos
“Automatic constructor was invoked” 并没有发生。C# 也没有这个“自动构造函数”。 - Marc Gravell
3个回答

8
不可以 - Java根本不支持自定义值类型,构造函数也必须显式调用。
但是,您对C#的理解也是错误的。从您最初的帖子中可以看出:
// Automatic constructor was invoked
// This line is same as MyStruct mStruct = new MyStruct();
MyStruct mStruct; 

那并不是真的。在这里,你可以无需进行任何明确的初始化就可以向 mStruct.i 写入,但是除非编译器知道所有的值都已经被赋值,否则你不能从中读取:

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

不,你在Java中总是需要显式调用构造函数。

由于可能存在多个构造函数,显式调用特定的构造函数可能是一个很好的实践。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接