I am learning JAVA and following the book JAVA:The Complete Reference by Herbert Shildt.
I learned about abstract classes in Java, but could not understand reason behind this line:
An abstract class cannot be directly instantiated with new operator.
I searched over web and stackoverflow and followed these questions: Why can't we instantiate a abstract class in JAVA? and Why can't we instantiate an interface or an abstract class in java without an anonymous class method?
In one answer, someone wrote as:
Simply, in a good object oriented program, you should never want to instantiate an abstract class or interface. If you do, the design is probably wrong.
I do not understand why it is important not to instantiate an abstract class for good OOP
design. If someone can give a good explanation, then please help.
Abstract classes sole purpose is to be extended. The abstract class will contain common code for all its subclasses and the subclasses will only implement those sections that is relevant to it.
Abstract classes are quite useful for the Command pattern. For example, let's say you have a task that needs to execute a set of actions, then you can define a Command abstract class:
The idea now is that you can implement a whole range of commands, for example:
...and also
Now, you can have something like this:
Now it's easy to add more commands later, by simply extending the Command abstract class and implementing the runInternal() method. As with all things, this pattern can/is heavily abused, but in the right environment is makes for easy/readable code.
Abstract classes are meant to provide a skeleton structure so there is no concrete implementation in them.
The child classes are expected to fill in the implementation and hence they can be instantiated.