No announcement
 

Abstraction

Data abstraction is the property/process by virtue of which we hide certain details and show only the essential details to the user. Simply, it is the process of hiding the implementation details from the user, and exposing only the functionality to the user.

Abstraction can be achieved using Abstract classes and Interfaces.

Abstract Class

An abstract class is a declared with an Abstract keyword, and is a restricted class that cannot be instantiated. An abstract class can have both abstract and regular methods.

Abstract Method

An abstract method is declared with an abstract keyword and does not have a body. The body/implementation is provided by the sub class.

Example:

AbstractionDemo.java

package com.codingnous.tutorial;

public class AbstractionDemo {

	public static void main(String[] args) {

		// Create object of class.
		Calculator c = new Calculator();

		// Invoke implemented square method.
		System.out.println("Square of 8 is " + c.square(8));

		// Invoke message method from abstract class.
		c.message();

	}

}

// Declare abstract class.
abstract class Computation {

	// Abstract function, should be implemented in sub class.
	abstract int square(int num);

	// Regular method inside abstract class.
	public void message() {
		System.out.println("Abstraction Demo.");
	}
}

// Extending abstract class in sub class.
class Calculator extends Computation {

	// abstract method must be implemented in sub class.
	@Override
	int square(int num) {
		return (num * num);
	}

}

Output
Square of 8 is 64 Abstraction Demo.