简体   繁体   中英

Why should we use 2 constructors when implementing Linked List?

Professor showed us the implementation of linked list and nodes in java. Node started with this:

private class Node{

  private T data;
  private Node next;

  private Node(T data){
    this(data,null)
  }

  private Node(T dataP, Node nextN){
   data = dataP;
   next= nextN;
  }

}

What is the reason for using two distinct constructors? Client can call the 2nd constructor with Node null, if he wants to. Professor said it wasn't to make it easier on the client, too. I know Java creates default constructor if you don't provide one, but is this really about making sure there are no errors in this case? If so, what would be the error to arise in a situation where we don't have default constructor?

There is no need of having both constructors. It's probably just an example given by your professor, of two constructors, and example of one of them using another.
In your example new Node(someKindOfVariable, null) using the second constructor, is the same as new Node(someKindOfVariable) using the first one. So there is no necessity in having the first constructor.

Sometimes, you want to have more constructors (overloading) for both convenience and readability when instantiating the objects. Even though private constructors are not meant to be called by other classes, it may be viewed or used again by another programmer who is reviewing or maintaining the class.

In your case, Node(data) is short hand for Node(data,null) , because other programmers may not know how to instantiate a single Node with no next defined.

Having more constructors would be more helpful for non- private classes ( public , protected or default ) since other programmers may extend or reuse your class and its constructors. Having additional constructors can allow different ways of instantiation.

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