I have a class called "Module"
public abstract class Module {
protected Map<String, Port> ports;
...
public Map<String, Port> getPorts() {
return ports;
}
}
and a class called Design that is a subclass of Module
public class Design extends Module{
...
//want to do this but doesn't compile
@override
public Map<String, Port> getPorts() {
return (Map<String, TopPort>) ports; //TopPort is a subclass of Port
}
}
Basically what I want to do is only add TopPorts to Design and have the type already cast upon return from the getPorts() function.
What I am doing right now is casting Ports to TopPorts after the getPorts function returns in main, but this is very finneky and someone who is building on my code would not be able to immediately understand when a TopPort is returned.
I also tried creating another function instead of overriding getPorts()
//want to do this as well but doesn't compile
public Map<String, TopPort> getTopPorts() {
return (Map<String, TopPort>) ports; //TopPort is a subclass of Port
}
What is the correct way to do this?
More specific problem
I have been playing around with the code and I am able to add this in my "Design" class:
public TopPort getTopPortByName(String porName) {
return (TopPort) ports.get(porName);
}
public void addPort(TopPort port) {
this.ports.put(port.getName(), port);
}
However whenever I try to do this casting, it doesn't work:
return (Map<String, TopPort>) this.ports;
Why does the type-cast not work on the whole map even though it works on each of its members?
You'd need to make your class generic.
public abstract class Module<P extends Port> {
protected Map<String, P> ports;
public Map<String, P> getPorts() {
return ports;
}
}
class Design extends Module<TopPort> { }
I'm not sure if this isn't overkill here, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With