Abstraction in Java

Overview

It is a process of hiding implementation details and showing only the functionality of a class to a user. Abstraction is achieved by abstract class or interface.

Abstract class is a special class in Java, it can not be instantiated, means you can not create an object of this class and that's why you can not use it directly.

Where do you use Abstract Class in Java?

  1. If you want know, where an object of a class is created in a project. Simply mark the class as abstract. The compiler will automatically list down where the object is created.
  2. While creating an instance of Enumset.
  3. To avoid code duplication you can use Abstract class. For e.g. If a company has Permanent Employee and Contract Employee, then you can create an abstract class of Employee and declare all the common properties and methods (abstract method) in it. 

Abstract Class vs Interface

Do's and Dont's

  • You cannot create instance of an abstract class in Java. For example if a class ABC is abstract than code like ABC instance = new ABC() will result in compile time error. You can use factory method to create object instead of directly calling constructor. e.g.
  • Fruit mango = new Mango(Color.YELLOW, true);
  • To create a concrete class by extending abstract class, you must override all abstract method. For example if a class ABC has an abstract method abc() then a class EFG, which extends ABC must override abc() to be a concrete class.
  • A class can be abstract even without any abstract method. 
  • Both top level and nested class can be made abstract in Java.
  • Constructors are allowed in an abstract class because you can't create an object of such class.
  • Abstract classes can also have final methods (the method which you can't override).
  • We can define static methods in an abstract class.

Comments

Popular posts from this blog

HashMap, TreeMap and LinkedHashMap difference

Language Fundamentals in Java

Collections in Java