You are getting a StackOverflow because the parent constructor is always called (see also: https://stackoverflow.com/a/527069/664108). In your case this results in endless recursion.
To avoid that, you will have to add a check in the Node constructor and call it explicitly from the NullNode constructor:
public class Node
{
Node nextNode;
char key;
Node prevNode;
Node() {
Node(true);
}
Node(boolean createNullNodes) {
if (createNullNodes) {
nextNode = new NullNode();
prevNode = new NullNode();
}
}
}
public class NullNode extends Node
{
NullNode() {
super(false);
}
}
A better solution for the NullObject pattern is using interfaces. This eliminates the constructor problem and also allows to remove the not needed nextNode and prevNode variables from the NullNode.
Example with interface:
public interface INode
{
public char getKey();
public INode getNext();
public INode getPrev();
// ...
}
public class Node implements INode
{
Node nextNode;
char key;
Node prevNode;
Node() {
nextNode = new NullNode();
prevNode = new NullNode();
}
public char getKey() {
return key;
}
public INode getNext() {
return nextNode;
}
public INode getPrev() {
return prevNode;
}
}
public class NullNode implements INode
{
public char getKey() {
return null;
}
public INode getNext() {
return this;
}
public INode getPrev() {
return this;
}
}
superkeyord? You can call the super-constructorsuper().NullNodeto avoid endless recursion.