Restricting sub-class declaration
I have an application where I want all my model classes to implement a specific update
method. For this I created an abstract class
and an interface
with the following declaration:
public interface BaseInterface<T>
{
T update(T t);
}
public abstract class BaseClass<T extends BaseClass<T>> implements BaseInterface<T>
{
}
Hence all my model classes will extend BaseClass
. For example a Book
class definition will be
public class Book extends BaseClass<Book>
{
public Book update(Book b)
{
//implementation
}
}
However using the above construct I am not able to restrict declarations of my model classes. For example while it is valid and required for the Book
class to extend BaseClass<Book>
, the following declaration also valid:
class Book extends BaseClass<User>
{
public User update(User u)
{
//implementation
}
}
While it is syntactically correct to do the above I want to restrict that.
Basically I want my model classes' update
method to take as parameter an instance of its own class and return an instance of its own class and nothing else.
In other words, if there is a class C
that extends BaseClass
, then its update
method must be of the exact signature C update(C c)
.
Or in other words if there is a class 开发者_开发知识库C
that extends BaseClass
, then the template parameter for BaseClass
must be C
itself [ie C extends BaseClass<C>
] and nothing else.
How do I achieve that?
NOTE: This is somewhat similar to the enum
declaration
public class Enum<E extends Enum<E>> implements Comparable<E>
{
int compareTo(E e)
{
}
}
Here we are able to restrict the definition of compareTo
method to take an instance of its own type of enum
and not any other kind of enum
.
Thanks in advance.
Change definition of you interface to interface BaseInterface<T extends BaseClass<T>>
.
Please follow my example:
public interface BaseInterface<T extends BaseClass<T>> {
T update(T t);
}
public abstract class BaseClass<T extends BaseClass<T>> implements
BaseInterface<T> {
}
public class Book extends BaseClass<Book> {
@Override
public Book update(Book b) {
return null;
}
}
class User {}
// This code cannot be compiled exactly for reason you want.
public class Book2 extends BaseClass<User> {
@Override
public Book2 update(Book2 b) {
return null;
}
}
精彩评论