Is Connection Connection polymorphism?

1
Connection connection;
connection = new ConnectionFactory().getConnection();

Can I say that doing this is polymorphism?

The Connection receives the connection of class ConnectionFactory .

    
asked by anonymous 13.02.2016 / 19:20

1 answer

9

Yes.

The method's return type getConnection is the interface Connection . So, you're just seeing the interface, not the implementation, which can be of various "flavors."

Defining polymorphism

The initial definition in Wikipedia for polymorphism is somewhat misleading, in defining the term as " references of more abstract class types represent the behavior of concrete classes ".

This may imply that polymorphism only exists when there is inheritance , which is not true.

However, it is clear from the foregoing that this was only a simplification, since the text goes on to say that with polymorphism " it is possible to treat several types in a homogeneous way (through the interface of the more abstract type) and that " one of the ways to implement polymorphism is through an abstract class, ".

In short, there are several types of polymorphism, one of which is using extension or inheritance mechanisms. It is worth remembering that in some languages there may be multiple inheritance, that is, inherit several classes, while in Java this is done using interfaces. As for the polymorphism, the result of both techniques is practically the same.

Multiple connection types, one interface

The vast majority of real (non-academic) applications use some kind of Connection .

The simplest example is when you use a pool of connections, because close does not actually close the connection, but returns to the pool of available connections.

This is done by implementing a different Connection that encapsulates the real connection, that is, another class that also implements Connection .

The entire JDBC API is done using polymorphism so you are always using abstract types or interfaces and never directly implementations. This makes your code work well with all the different types of databases supplying all the different implementations (with the exception of the SQL code exception).

Example without polymorphism

If the JDBC API was not implemented with polymorphism, we would have to instantiate and reference specific classes for each different type of bank or library.

Examples:

MySqlConnection con1 = mySqlConnectionFactory.getConnection();
MySqlStatement st1 = con1.createStatement("select * from tabela");
MySqlResultSet rs1 = st1.executeQuery();

OracleConnection con2 = oracleConnectionFactory.getConnection();
OracleStatement st2 = con2.createStatement("select * from tabela");
OracleResultSet rs2 = st2.executeQuery();
    
15.02.2016 / 03:02