问题
Suppose I have a type family, I have defined a set of methods in base type:
interface Foo<T> {
Foo<T> a();
Foo<T> b();
...
}
And Bar extends Foo
interface Bar<T> extends Foo<T> {
Bar<T> a();
Bar<T> b();
...
}
And then Zee extends Bar
interface Zee<T> extends Bar<T> {
Zee<T> a();
Zee<T> b();
...
}
When I implement this type family with different decorators, I found I constantly write something like
class XBar<T> extends XFoo<T> implements Bar<T> {
Bar<T> a() {
return (Bar<T>)super.a();
}
Bar<T> b() {
return (Bar<T>)super.b();
}
...
}
It is really tedious. I am wondering is this normal case in Java API design or I did something wrong, or there is sort of smart way to workaround the constant typecast with one line of code?
Updates, To answer your comments and response, yes, method chain is one thing I want to achieve here. BTW looks like the BaseStream type declaration in Java8 is a good example of addressing this problem. I am trying to use that approach. Will update my progress here.
Updates 2, The BaseStream approach doesn't work when I have multiple inheritance levels. See Java inherited Fluent method return type in multiple level hierarchies
回答1:
Why do your subclasses need to return the subclass type?
The Liskov Substitution Principle states that objects can be replaced by subtypes without altering any properties so if you code your classes correctly, then you don't need the cast especially if you are just returning the result from super.
The only time I can think of that has this problem is method chaining (like builder pattern) when you need to access extra subclass methods during the chaining... But that should be rare.
来源:https://stackoverflow.com/questions/19256811/java-api-design-narrow-return-type-in-methods