Adding functionality to implementation classes without changing the implemented Interface
<p>I have got an interface that defines some service methods for data retrieval:</p>

<pre><code>public interface DataReceiver {
    public Data getData();
}
</code></pre>

<p>Then i have a class that implements this interface and loads the data through a connection. I supply this connection using constructor injection:</p>

<pre><code>public class ConnectionDataReceiver implements DataReceiver {
    private Connection connection;

    public ConnectionDataReceiver(Connection connection) {
        this.connection = connection;
    }

    public Data getData() {
        return connection.query("blabla");
    }
}
</code></pre>

<p>This works pretty nicely. I can instantiate my <code>ConnectionDataReceiver</code> objects using the constructor, or i could add a factory method/class that extends the usability by providing an option to select a config file for connection setup. I then use my new class through my interface, so i can easily swap out the implementation (like loading the data from a file instead of a connection).</p>

<p>But what if i want to change my connection during runtime, without instantiating a new <code>ConnectionDataReceiver</code>? I would have to add getters and setters for my class. But since they are not part of my public service definition, i can't put them in my interface. I could use the implementation object in my code to set a new connection, but it feels pretty awkward hanging onto a reference to the original object only for maybe changing the connection object:</p>

<pre><code>ConnectionDataReceiver conDataRec = new ConnectionDataReceiver(myConnection);
DataReceiver dataRec = conDataRec;
// use dataRec

conDataRec.setConnection(myNewConnection);
// use dataRec again
</code></pre>

<p>In this example it would be the easiest way to just instantiate a new <code>ConnectionDataReceiver</code> and just reassign <code>dataRec</code>, but what if the instantiation of my object is really expensive? How do i give my implementation classes additional functionality while still being able to use my old service interface? Or is it generally frowned upon changing data at runtime, when the interface doesn't define that functionality?</p>