简体   繁体   中英

how can you pass an object to a function as a parameter, then have the function to assign a new object of a subtype to its parameter?

I'm trying to build up a compiler using the recursive descent parsing method and visitor pattern for semantic checking with Java. The thing that confuses me is to use visitor patterns, we have to create different subtypes. However, Java doesn't pass by reference. Which caused me that I cannot end up with the right subtype for each semantic records. Here is what I'm trying to implement

Node node = new ExprNode();
changeNodeType(node);

public void changeNodeType(Node node) {
     node = new AddOpNode();
}

then eventually my Node type will end up with AddOpNode(). Is there any way that I could eventually implement this in Java?

You could just return the new node type and assign it outside of the function.

Node node = new ExprNode();
node = changeNodeType();

public Node changeNodeType() {
     return new AddOpNode();
}

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