[英]Generic Interface in different classes
In my project, I have to use the database pretty often and I decided to create an interface and then implement it in different classes since they will all use the same methods. 在我的项目中,我必须经常使用数据库,并且我决定创建一个接口,然后在不同的类中实现它,因为它们都将使用相同的方法。
public interface Project<E> {
void createTable();
void insert(E obj);
E select(int id);
void delete(int id);
void update(E obj, int id);
}
I try to implement it in one of my classes like below: 我尝试在下面的我的一个类中实现它:
public class Person implements Project {
//createTable method
//select method
//delete method
public void insert(Person p) {
Connection connection = null;
PreparedStatement ppStm = null;
try {
connection = ConnectionConfiguration.getConnection();
ppStm = connection.prepareStatement("INSERT INTO person (first_name, last_name)"
+ "VALUES (?,?,?)");
ppStm.setString(1, p.getName());
ppStm.setString(2, p.getLname());
ppStm.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
} finally {
if (ppStm != null){
try {
ppStm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//update method similar to insert();
}
The problem is that when I try to override the insert() and update() methods it shows me an error message "the method must override or implement a supertype method" . 问题是当我尝试覆盖insert()和update()方法时,它向我显示一条错误消息“该方法必须覆盖或实现超类型方法” 。 I used generics since I thought it would work in my code seeing as I have different classes of different objects to implement it to but I am not understanding the right implementation I guess. 我之所以使用泛型,是因为我认为它可以在我的代码中工作,因为我可以使用不同类的不同对象来实现它,但是我猜不到我理解正确的实现。 I would like to know how I can change my interface or its implementation in my classes so it can work. 我想知道如何在类中更改接口或其实现,以便它可以工作。 Also when I remove the @Override it removes the error but still shows that I am not implementing all the methods. 另外,当我删除@Override时,它也会删除错误,但仍然表明我没有实现所有方法。 Thank you in advance. 先感谢您。
You can use DAO pattern 您可以使用DAO模式
public interface DAO<T> {
void createTable();
void insert(T t);
T select(int id);
void delete(int id);
void update(T t, int id);
}
Implementation 履行
class PersonDAO implements DAO<Person> {
@Override
public void createTable() {}
@Override
public void insert(Person person) {
/// Connection connection = null;
/// PreparedStatement ppStm = null;
// Detailed implementation
//// .............
}
@Override
public Person select(int id) {
return null;
}
@Override
public void delete(int id) {}
@Override
public void update(Person person, int id) {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.