Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change class variable type in subclass java

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?

like image 501
brinz Avatar asked Oct 19 '22 20:10

brinz


1 Answers

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.

like image 180
Thilo Avatar answered Oct 28 '22 22:10

Thilo