Reputation: 36028
Suppose I have a POJO User
,which I add some static method to do the CRUD operation:
public class User {
private String name;
private int age;
// getter and setter omitted
//
public static void add(User user) {
// add person
}
public static int delete(Object id) {
// delete person
return 1;
}
}
Since I have other entities like User,so I want to make the add
and delete
method abstracted,something like this;
public class?interface Entity<T>{
static add(T t);
static delete(Object id);
}
public class User extends Entity<User>{
@override
static add(User user){
// add ...
}
....
}
Is this possible?
Upvotes: 1
Views: 520
Reputation: 425033
You can't override static methods, but there is no good reason why these methods should be static. Make them instance methods:
The interface should look like:
public interface Entity<T> {
T getId();
void add();
int delete();
}
With implementations:
public void add() {
// add "this"
}
public int delete() {
// delete "this"
return 1;
}
This code pattern is very common - I've seen it many times - and it works well.
If you don't want to use instance methods, you can create static methods in a utility class to deal with such objects:
public class DaoUtil {
public static <T> void add(Entity<T> entity) {
// some impl
}
public static <T> int delete(Class<? extends Entity <T>> clazz, T id) {
// some impl
}
}
Upvotes: 1
Reputation: 14247
Don't make the CRUD methods static in the entity classes, create a generic DAO interface instead and then implement concrete DAO class for each entity type.
Don't use static methods for such scenario. A better and more OOP approach is to use a Dependency Injection framework that creates only one instance of each concrete DAO class to save memory and time (for creating new DAO instances again and again) and reuses those instances in all places in your application that need to access them.
public interface Dao<T> {
// you can customise these signatures by your needs
// these are just my suggestions
T get(long id);
List<T> getAll();
T add(T t);
T update(T t);
void delete(T t);
}
public class UserDao implements Dao<User> {
public User get(long id) { ... }
public List<User> getAll() { ... }
public User add(User user) { ... }
public User update(User user) { ... }
public void delete(User user) { ... }
}
Upvotes: 2
Reputation: 66637
No, it is not possible.
First you can't define static methods in interface. See this discussion
Second, You can't override
static
methods. See this discussion.
I am not sure about your requirement, if applicable, I would suggest leave them as instance methods and allow each class to provide it's own implementation (as Bohemian suggested).
Upvotes: 8