Java does not support multiple inheritance of implementation, but it supports multiple inheritance of interface. So, you can implement as many interfaces as you want.
To avoid duplicates and share code between several classes, you can use delegates.
For example:
- Interfaces:
interface IGas {
checkGas();
onLowGasEvent();
}
interface IBattery
checkBattery();
onLowBatteryEvent();
}
- implementations of common functionality
class GasImpl implements IGas {
checkGas() {
...
}
onLowGasEvent() {
...
}
}
class BatteryImpl implements IBattery {
checkBattery() {
...
}
onLowBatteryEvent() {
...
}
}
- Activities (pay attention to implementaion setion):
class GasCar extends Car implements IGas {
IGas mGasImpl = new GasImpl(); // create it in your own code, or inject to inverse dependencies, etc.
checkGas() {
mGasImpl.checkGas();
}
onLowGasEvent() {
mGasImpl.onLowGasEvent();
}
}
class BatteryCar extends Car implements IBattery {
IBattery mBatteryImpl;
checkBattery() {
mBatteryImpl.checkGas();
}
onLowBatteryEvent() {
mBatteryImpl.onLowBatteryEvent();
}
}
- And then your
HybridCar
will be something like this:
class HybridCar extends Car implements IGas {
IGas mGasImpl;
IBattery mBatteryImpl;
checkGas() {
mGasImpl.checkGas();
}
checkBattery() {
mBatteryImpl.checkBattery();
}
}
- If you want to work with
EventBus
, you should keep subscribers as an Activity interface - but delegate it's implementation to the handlers as well. So, in the HybridActivity
:
@Subscribe(threadMode = ThreadMode.MAIN)
function onLowGasEvent(){
mGasImpl.onLowGasEvent();
}
@Subscribe(threadMode = ThreadMode.MAIN)
function onLowBatteryEvent(){
mBatteryImpl.onLowBatteryEvent();
}
If onLow...Event
requires Context
, update interface methods to pass it as a parameter.
Hope it helps.