Use Abstraction to Simplify Design – Java Best Practices

In Java abstraction is accomplished by using Abstract class and Interfaces. Abstraction is one of the most important concept of OOPs. Abstract class is similar to Interfaces in Java, except that it can contain methods with implementations also.

Abstract Class In Java

abstract keyword is used to create a abstract class and method. An abstract class can never be instantiated. The sole purpose of creating an abstract class is that it needs to be extended by sub-classes. Though it can’t be instantiated, but you can compile and execute an abstract class.

Example:

if you try to instantiate a Car (abstract class) in the CarTest test class, you will get a compiler error as shown below

To extend the super class (abstract class) you need to use extend keyword as shown in the following example

Now let’s modify CarTest class like the following and run

Output

Advantages of Abstraction

Using abstract class and abstract methods you would achieve the following in your software design.

  • Generalization/Template – Abstract classes are templates for specific subclasses. A car has various attributes like model, price, year etc., and for every car the same set of attributes is applicable. So instead of declaring them separately in HondaCar, ToyotaCar etc., we have declared them in the abstract class. Also abstract methods goFast() and goSlow() is common for all the brands of car.
  • Re-usability/Common Logic – Abstraction helps in code re-usability or writing common logic that every subclass needs. You will write non-abstract methods (like whoAmI()) with implementations that shouldn’t change from Car type to Car. By using non-abstract methods in an abstract class all the concrete subclasses inherit method implementations and need to implement only the methods that define subclass-specific behavior.

Points to Remember

  • Abstract class cannot be instantiated
  • You can’t mark a class a both abstract and final. If you use combination of both modifiers, it would result in compile error.
  • Even if single method is abstract in the class, then the whole class must be declared as abstract.

Further Learning

References

Leave a Reply

avatar
  Subscribe  
Notify of