Search code examples
javainheritanceabstract-classparent-childgetter-setter

How to specify subclass of abastract parent's field


So what I'm trying to do is on an abstract class have a field and when this abstract class is inherited on their childs be able to have that field as a child of the class stated in the abstract parent.

For example I have an abstract Player class and then Client and Opponent (it'd be for a multiplayer game) that inherits Player. Player has a field of type Unit. Unit itself is inherited by ClientUnit and OpponentUnit. I know I can just pass a ClientUnit for my Client constructor and assign it as the Unit (inheritance, duh), but how would I have a getter that returns it on the form of a ClientUnit object without risking exceptions and what-not?

Edit: I've added some code to better explain the issue.

public abstract class Player {
    private Unit unit;        

    public void setUnit(Unit unit) {
        this.unit = unit;
    }
    public Unit getUnit() {
        return unit;
    }
}

public class Client extends Player {
    @Override
    public ClientUnit getUnit() {
        return (ClientUnit)super.getUnit();
    }
}

That seems to be working but I don't know if it's a safe/robust way of doing it.


Solution

  • I'm not sure I have understood your question, but maybe Type Parameters can help you:

    public abstract class Player<T extends Unit> {
    
        private T unit;
    
        public Player(T unit) { }
    
        public T getUnit() {
            return unit;
        }
    
        public void setUnit(T unit) {
            this.unit = unit;
        }
    }
    

    And the implementation class:

    public class Client extends Player<ClientUnit> {
    
        public Client(ClientUnit unit) { 
           super(unit); 
        }
    
        public static void main(String[] args) {
            Client client = new Client(new ClientUnit());
            ClientUnit unit = client.getUnit();
        }
    }