我对这段Java代码(一个名为Message的类)感到困惑.我认为第二个构造函数设置为data_length使用值初始化,为此它调用一个名为init你可以看到的方法.
但是内心发生的事情init是什么让我在我的桌子上猛烈抨击:D这个方法里面发生了什么?为什么要自称?
/**
* The actual length of the message data. Must be less than or equal to
* (data.length - base_offset).
*/
protected int data_length;
/** Limit no-arg instantiation. */
protected Message() {
}
/**
* Construct a new message of the given size.
*
* @param data_length
* The size of the message to create.
*/
public Message(int data_length) {
init(data_length);
}
public void init(int data_length) {
init(new byte[data_length]);
}
Run Code Online (Sandbox Code Playgroud)
我正在将此代码转换为C#,如果我这样做就没问题:
public class Message
{
//blah blah and more blah
private int _dataLength;
public Message(int dataLength)
{
_dataLength = dataLength;
}
}
Run Code Online (Sandbox Code Playgroud)
它不是在呼唤自己.如果你看这里:
init(new byte[data_length]);
Run Code Online (Sandbox Code Playgroud)
代码实际上是构造一个new byte[],然后在调用另一个init方法时使用.Java允许方法重载,因此并非所有init方法都相同.