This might be a simple question for many but has confused me. I am picking an example from Kathy Sierra that shows the utility of Abstract Classes but I am unable to underst
By making a method abstract, it means that people have to implement it. You require people to do so and it is impossible for people to forget to do so, as it will fail to compile if they do.
The @override
annotation exists for a very similar reason, by marking a method as @override
you get an error if (for example) you typed the method name wrong and aren't actually overriding something.
In many ways the abstract class is half way between an interface and a normal class - it defines what you need to do to use it in the same way an interface does, but it also handles some of the implementation for you.
Classes can only extend one other class. They can implement any number of interfaces.
For example you might have MotorVehicle
inherited by Car
, Motorbike
and Train
- but then you might have a Steerable
interface implemented by Car
, Motorbike
and Pedalbike
.
To answer the question in the comments:
If there is an Interface "I" having method m() which is implemented by class "A" and another class "B" wants to access the method m(), what is the need of interface here. Can we simply not implement that method in class A?
You can - but if on the other hand class B
wants to access the method m()
in both a class A
and class C
(where A and C don't inherit from each other or a common class containing m()) then the way to do that is to specify a common interface I and class B uses the interface type, I, not the types A and C at all.
Also remember that interfaces can be used between packages and libraries. For example Listener and Strategy patterns make heavy use of interfaces. When the Java developers wrote JButton
(for example) the ActionLstener
is specified as an Interface to provide maximum flexibility to people using JButtons
in the future.