Fri Jan 19 2018

Abstract class in Java

Abstract class in Java

In object-oriented programming, abstraction is a process of hiding the implementation details from the user and only showing functionality. In simple word, the user will have the information on what the object does instead of how it does. In Java, abstraction can be achieved in two ways - using abstract class and interface. So, let's talk about the abstract class in Java.

In Java, abstract classes are similar to interface except the default method implementation. Classes are defined abstract using abstract keyword. It can contain an abstract method without body and also methods with implementation. It's mostly used to provide a base for subclasses to extend and implement the abstract methods and override or use the implemented methods in the abstract class.

So, how does it work?

When you define a class as abstract, it works as a generalized form or structure of all the subclasses. Consider an ‘employee’ as an example, all have certain states (name, employee id, address, phone, etc.) and behaviors (check in time, get salary, etc.). From this, specific types of employees such as manager, group leader, designer, programmer, etc. have additional characteristics and behaviors like problem solving capabilities, creative thinking, instruct every member of the group etc.

This is the perfect situation for implementing abstract class. You can take advantage of the similar characteristics & behaviors by inheriting from the same abstract parent object of the class, also add their own characteristics.

Some important points about abstract class in Java

  1. Abstract class in Java can’t be instantiated.

  2. If a class has abstract methods, then the class should also be abstract, else it will not compile.

  3. It’s not necessary to have an abstract method in abstract class.

  4. Its better to use interface, if the abstract class doesn’t have any method implementation. Because Java doesn’t support multiple class inheritance.

  5. The subclass of abstract class in Java must implement all the abstract methods unless the subclass also acts as an abstract class.

  6. A Java abstract class can implement interfaces without even providing the implementation of interface methods.

  7. The Java abstract class is used to provide a common method implementation to all the subclasses or to provide a default implementation.

  8. Abstract class in Java can be run as other class if it has main() method.

Advantage of abstraction

  1. Avoids code duplication and increases reusability.

  2. Reduces the complexity of viewing the things.

  3. Increase security of an application or program.

A suitable example for Java abstract class will come soon.

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.