Reputation: 777
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..
Upvotes: 0
Views: 156
Reputation: 1806
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.
Upvotes: 0
Reputation: 8561
- 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);
Upvotes: 1