Reputation: 10949
I have this Java code:
public interface User{
public void in(Message message);
}
public interface Message{
//....
}
public interface WebsiteMessage extends Message{
//....
}
public class WesiteUser implements User{
@Override
//I'm not allowed to do this
public void in(WebsiteMessage message){}
}
Is there a way I can implement the in
method with WebsiteMessage parameter?
For the moment I'm doing something like this:
@Override
public void in(Message message){
WebsiteMessage msg= (WebsiteMessage) message;
//..
}
Upvotes: 1
Views: 65
Reputation: 140525
Just to give a different perspective: the Liskov Substitution Principle basically tells you ... to not do that.
The idea of that principle is that in order to be sound, you should be able to replace any usage of the "base" type with the "derived" type. And that doesn't work if you restrict parameters of methods. Because when calling the method on the base class, you are allowed to use the "wider" type; which gives you an error when you try it on the derived class.
It is fine to restrict the return type; or to widen method parameters; but not the other way round.
And if you turn here you find people arguing if LSP also applies when talking about interfaces.
Long story short: even when the solution proposed by shmosel works; you might want to step back and consider if that is really the best way to solve your problem. You see, sound OO design and inheritance is more than just putting extends here or there.
Upvotes: 3
Reputation: 50726
You can do it with a bounded type parameter:
public interface User<M extends Message> {
public void in(M message);
}
public class WebsiteUser implements User<WebsiteMessage> {
@Override
public void in(WebsiteMessage message) {}
}
Upvotes: 5