I have an interface at the top of my program (IVehicle
), below this is a class which implements the majority of the inherited methods (Vehicle
).
Below Vehicle
is two more classes, Fueled
, and Non-Fuelled
.
Fueled
needs methods to get/set/increment the fuel
field, Non-Fulled
doesn't.
My problem is that without putting the methods into the interface, when I try to call them from elsewhere in my program Java won't allow it - I either have to cast (which I don't believe is an option here as I have two separate types of Vehicle
) or create the method.
Is there anyway to deal with this, other than creating a method in the interface?
If that is the only option, how would I deal with the Inheritance in the Non-Fuelled
class?
The whole point of an interface is that it represents a level of abstraction - you're saying "All types that implement this interface support these operations."
It sounds like the operations of "change the fuel field" simply don't belong in that interface, because they're not common to all implementations. Code using the interface can't call those operations, because they may not be supported by the implementation.
You can cast, if you really want to:
if (vehicle instanceof Fueled) {
Fueled fueled = (Fueled) vehicle;
// Perform Fueled-specific operations here
}
... but that's usually (not always, but usually) a sign that your design has gone astray, and you should really think about it more carefully. It's coupling this code very tightly to Fueled
.
Or you could add the operations to IVehicle
(which isn't a conventional name for an interface in Java, by the way) and just implement them with no-op methods where they don't make sense. But that's a bit of a design smell. Sometimes it may be the cleanest approach, but try to avoid it.
(It's hard to give concrete advise without having the real design situation in front of us.)
See more on this question at Stackoverflow