-6

I want to create a generic database connection class which handles all the incoming database query for different types of classes.

I've wrote a generic interface

public interface IDBConnection<T> {

public void createOrUpdate(T t);
public void delete(T t);

public void initConnection();
public void closeConnection();
} 

and implemented it into the database connection class

public class GenericDBCon implements IDBConnection {

private static JdbcConnectionSource con;


@Override
public void createOrUpdate(Object t) {

}

@Override
public void delete(Object t) {

}

@Override
public void initConnection() {

}

@Override
public void closeConnection() {

}
}

I don't understand why the implementation of, lets say the createOrUpdate-function has an "Object t" as parameter instead of "T t" like in definition of the interface?

Jesper
  • 202,709
  • 46
  • 318
  • 350
0apm
  • 11
  • 1
  • 3
  • 1
    You are using `IDBConnection` without a type argument in the line `public class GenericDBCon implements IDBConnection`. See [What is a raw type and why shouldn't we use it?](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Jesper Jun 22 '16 at 10:16

2 Answers2

1

The reason why is that you are not including the generic declaration in either of the classes' headers, so it defaults to Object.

You will need to change the header of the IDBConnection class to

public interface IDBConnection<T>

and the header of the GenericDBCon class to

public class GenericDBCon<T> implements IDBConnection<T>

or

public class GenericDBCon implements IDBConnection<SomeClass>

The second alternative for GenericDBCon provides a specific class as the generic, rather than getting one provided by some other piece of code (e.g a variable declaration: GenericDBCon<MyClass> dbCon = new GenericDBCon<MyClass>).

SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
0
public interface IDBConnection<T extends Model> {

public void createOrUpdate(T t);
public void delete(T t);

public void initConnection();
public void closeConnection();
} 

//All classes should extend this interface.

public interface Model {
    //Define common table properties here which are used in create and delete
}

public class GenericDBCon<T extends Model> implements IDBConnection<T extends Model> {

private static JdbcConnectionSource con;


@Override
public void createOrUpdate(Model t) {
    //Now it is ensured that the classes are of type model
}

@Override
public void delete(Model t) {

}

@Override
public void initConnection() {

}

@Override
public void closeConnection() {

}
}
Jaiprakash
  • 599
  • 2
  • 7