Tyler Whalen Tyler Whalen - 1 month ago 9
Java Question

Java generic abstract method parameters

I am trying to gain a better grasp on abstraction and have run into a problem.

I have the following classes:

Abstract class:

public abstract class Box {
abstract <T extends Mass> void putMassInBox(T mass);
}


Implementations:

public class CircleBox extends Box {

@Override
void putMassInBox(Mass mass) {
CircleMass circleMass = (CircleMass) mass;
}

}


The one below causes an error, because it doesn't recognize a SquareMass as a Mass, or I am telling it the incorrect way to do it.

public class SquareBox extends Box {

@Override
void putMassInBox(SquareMass mass) {
// TODO Auto-generated method stub

}

}


Here is the Mass interface:

public interface Mass {

}


And here are its implementations:

public class CircleMass implements Mass {

}


public class SquareMass implements Mass {

}


So I want to force a method that takes parameters based on which implementation it is. I know that I can cast the mass like in the circleMass example, but I was wondering if that was the best way to do it? Is it possible to force a method that takes any object extending a different object? Is it worth the extra effort or is casting the standard way of making this kind of abstraction.

Answer

You have to make the class generic, not the method:

public abstract class Box<T extends Mass> {
    abstract void putMassInBox(T mass);
}

public class CircleBox extends Box<CircleMass> {

    @Override
    void putMassInBox(CircleMass mass) {
    }   

}