Abstract Classes in Java

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

Why to make a class if you can’t make objects out of it?

Because no one would create a generic, abstract Car object as they would not be able to initialize its state like color, price, model etc.,

And programmers need to instantiate actual car types (derived types) such as  HondaCar  and  ToyotaCar .

The above code will compile fine. However when you try to instantiate, you will get compile error like the following

Note:
  • An  abstract  class has a  protected  constructor by default.
  • The methods marked abstract ends with semicolon and will not have an implementation. Such methods are called abstract methods.
  • Even if single method is abstract , then the whole class must be declared abstract . However, you can put non-abstract methods in abstract class.
  • By having non-abstract methods in an abstract class, you are providing inherited method implementations to all its concrete subclasses. Concrete subclasses need to implement only the methods that are abstract.
  • You can’t mark a class both  abstract  and final . They both have nearly opposite meanings. An abstract class must be subclassed, whereas a final class must not be subclassed.
Creating concrete subclass

Exam Watch:

If you see the combination of  abstract  and  final  modifiers used in your code, the code will result in compile error.

Leave a Reply

avatar
  Subscribe  
Notify of