First case,
DongleManager dongle = new SimulatedDongle();
dongle.getConnected();
dongle.connect(); // Erorr!!
It fails in the connect
because, you can only override methods which are defined in the parent class. In this case, DongleManager
doesn't have connect
. So, it fails.
Second case,
IDongle dongle = new SimulatedDongle();
dongle.getConnected(); // Error!!
dongle.connect();
You are assigning an object of DongleSimulator
to IDongle
reference, which has only connect
defined in it, not getConnected
. That is why it fails.
I would recommend designing your system, like this
interface IDongle {
public abstract boolean connect();
}
abstract class DongleManager implements IDongle {
private boolean connected = false;
public void setConnected(boolean status) {
connected = status;
}
public boolean getConnected() {
return connected;
}
}
class SimulatedDongle extends DongleManager {
@Override
public boolean connect() {
return true;
}
}
class RealDongle extends DongleManager {
@Override
public boolean connect() {
return true;
}
}
If you look at the DongleManager
, it implements IDongle
and the children of this class only extend DongleManager
.
Live Demo of the working solution
Note: Since getConnected
is defined only in DongleManager
, IDongle
interface will not have any idea about it. So, the following will still fail.
IDongle dongle = new SimulatedDongle();
dongle.getConnected();
// error: cannot find symbol
dongle.connect();
If you want to make that possible, then you need to include that also in the IDongle
, like this
interface IDongle {
public abstract boolean connect();
public boolean getConnected();
}