Reputation: 14112
I am really confused by this piece of Java code (a class called Message). I think the second constructor is set to initialize data_length
with a value, and for this purpose it calls a method named init
as you can see.
But what is going on inside init
is what makes me bash my head on my desk :D What is happening inside this method? Why it is calling itself??
/**
* 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]);
}
I am converting this code to C#, is it fine if I do just:
public class Message
{
//blah blah and more blah
private int _dataLength;
public Message(int dataLength)
{
_dataLength = dataLength;
}
}
Upvotes: 0
Views: 94
Reputation: 417592
Recursion is allowed in Java, but in your example init()
isn't calling itself but another init()
method which takes a byte array as its argument (which you didn't include in the code you posted).
Upvotes: 2
Reputation: 206796
public void init(int data_length) {
init(new byte[data_length]);
}
It is not calling itself; it's calling another method named init
that takes a byte[]
as a parameter.
The class Message
or one of its superclasses contains that other init
method - you didn't show it to us.
Creating different methods with the same name but different parameter types is called method overloading.
Upvotes: 3
Reputation: 14223
It isn't calling itself. If you look here:
init(new byte[data_length]);
The code is actually constructing a new byte[]
, which is then used in the invocation another init
method. Java allows method overloading, so not all init
methods are the same.
Upvotes: 7