简体   繁体   中英

Recursive call in Java methods allowed?

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;
     }
 }

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.

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 .

Java中允许进行递归,但是在您的示例中, init()并不调用自身,而是另一个init()方法,该方法以字节数组作为参数(您未在所发布的代码中包含它)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM