Java Abstraction

In object-oriented programming, abstraction is all about hiding the implementation details from the user. In the end the user will only know what this function does instead of how it does. One of the way to achieve Java abstraction is through a class contains abstract keyword.

Abstraction is the quality of dealing with ideas rather than events. For example, if we have abstract bank class with one abstract interestRate() method . The definition and logic of calculating interestRate() will be different depending on the bank.

Abstract class

A class contains abstract keyword in declaration known as Abstract class.

// abstract class
abstract class TestClass {

}

Abstract Class Rules:

  1. Abstract class may or may not have abstract functions.
  2. If any method defined in the class as abstract than the class must have abstract keyword.
  3. Abstract class cannot be instantiated.
  4. Abstract class need to inherit in other class for usage.
  5. The child class which is implementing Abstract class need to declare itself as abstract or implement all abstract methods to instantiate that class.
  6. An abstract class can have data member, abstract method, define method(non abstract method) and constructor.

Abstract method

A Method contains abstract keyword in declaration known as Abstract method. We may have any number of abstract methods in a class.

// abstract class
abstract class TestClass { // abstract method
abstract void addition();
}

Abstract Method Rules:

  1. A class can have any number of abstract methods.
  2. Class need to be declared as abstract if we have declared single abstract method in the class.
  3. Abstract method doesn’t contain any method definition.

Example:

In the below example, there is a constructor defined with the abstract method print() in the abstract class Shape.

Sub class Circle extends the parent Shape class and override its print() method.

In the Test public class created a Shape object having a Circle class reference to execute the print() method.

OUTPUT:

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan