I have to code a school project, to do that, they gave us some interfaces to help us to design the class implementations.
INode
is one of them :
public interface INode {
void buildString(StringBuilder builder, int tabs);
}
We have to implement this interface several times.
BlockNode
is one of them :
public class BlockNode implements INode {
@Override
public void buildString(StringBuilder builder, int tabs) {
}
}
Now my problem is that in the main function they do that (the type of parse is INode):
root = parser.parse();
builder = new StringBuilder();
builder.append("PARSE TREE:\n");
root.buildString(builder, 0);
I don't get which implementation of
buildString(StringBuilder builder, int tabs)
is called. It could be the one I wrote above (BlockNode) ? or any other I implemented ? I don't understand which one is called in first..
2 Answers 2
- This will invoke method from BlockNode
INode root = parser.parse(); // Let's assume it return new BlockNode();
builder = new StringBuilder();
builder.append("PARSE TREE:\n");
root.buildString(builder, 0);
- This will invoke method from SomeNode
INode root = parser.parse(); // Let's assume it return new SomeNode();
builder = new StringBuilder();
builder.append("PARSE TREE:\n");
root.buildString(builder, 0);
Comments
Let's assume we have a Parser Class.
public Parser {
public INode parse(){
return new BlockNode(); // this will return a new BlockNode.
}
}
Now if you want to identify what type would it be to return to you without seeing the parse method. You can change your method in your INode
from:
void buildString(StringBuilder builder, int tabs);
to:
String buildString(StringBuilder builder, int tabs);
and then when you implement it on your class nodes:
public class BlockNode implements INode {
public String buildString(StringBuilder builder, int tabs) {
return "BlockNode";
}
}
or
public class OtherNode implements INode {
public String buildString(StringBuilder builder, int tabs) {
return "OtherNode";
}
}
Now, in this way you can distinguish what type is return by printing it.
root = parser.parse();
builder = new StringBuilder();
builder.append("PARSE TREE:\n");
String nameOfClass = root.buildString(builder, 0);
System.out.println(nameOfClass); // this will identify what type is returned.
INodeis returned byparse(), of course. You can't tell by inspecting this code.parserto see whatparse()returns we cannot tell you. The whole point of using interfaces is thatparse()returns an appropriate implementation that provides the necessary functionality, and you don't actually need to know which one.parse()is doing, nor what the differences are between your concrete classes (i.e.BlockNodeand the other ones). You have to decide which implementation to return based on your requirements.