×

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process for hiding the implementation details from the user. Java developers can only provide the functionality to the user and hide the implementation detail using abstraction. Abstraction is one of the most important features of oops. It is achieved using abstract classes and interfaces. Java uses a keyword 'abstract’ to make a class abstract. Suppose a user is making a call to another user. He is simply enjoying the service, but he has no idea about the functionality of how things are working, this is called an Abstraction. Let's understand it with a programming example. Suppose you are making a banking application and you are asked to collect all the information of the customer. Then there is a chance that you will come up with some additional info about the user like favorite movie, favorite Actor, but all these information are not necessary to create an application. So you need to select only the useful information for your project from that collection of data. Since we can fetch/ remove/ select the information from that collection of data, this process is referred to Abstraction.

How to achieve Abstraction in Java?

There is two way to achieve abstraction in Java.
  • Java Abstract classes (0 to 100%)
  • Java Interfaces (100%)
Example This is an example of Java Abstraction.
abstract class Fortuner{
abstract void speed();
}
class Car extends Fortuner{
void speed(){
System.out.println("Speed is 220 km/h");}
public static void main(String args[]){
Fortuner obj=new Car();
obj.speed();
}
Output
Speed is 220 km/h
Above example describes that how the abstraction achieved in java. Class Fortuner and method speed() is abstracted in the given example.

Java Abstract classes

An Abstract class is a class that contains abstract as well as concrete methods. A class is created Abstract using the keyword 'abstract’. An Abstract class can't be instantiated, in other words. We cannot create the object of an abstract class. Abstract class can have both abstract and concrete methods. abstract class Account{ public abstract void debit(); public void credit() { System.out.println(“Account Statement”)}} If we create the object of the given class Account then it will produce an error. Account obj=new Account(); //it will produce an error To use the abstract class, we must inherit it from the other class. Abstract methods in abstract class do not have a body. We can achieve 0 to 100 percent abstraction using Java abstract classes. See the Example below
//Abstract class
abstract class Transaction {
public abstract void credit();
public void debit() {
 System.out.println("Account is debited");
}
}
//Subclass (inherit from Transaction)
class Account extends Transaction{
public void credit() {
 // The body of credit() is provided here
 System.out.println("Account is credited");
}
public static void main(String[] args) {
 Account obj = new Account();
 obj.credit();
 obj.debit();
}
}
Output
Account is credited
Account is debited

Java Interface

Java interface is a collection of abstract methods and static constants. It’s like a class that contains only static constants and abstract methods. We can achieve 100 % abstraction using Interfaces. The interface does not contain any constructors. Methods in an interface are only public and abstract. The interface is responsible for what a class will do; it is like a blueprint of the class.  Java uses interfaces to achieve multiple inheritances. To use an interface in a class, use the keyword implements after the interface name. Java class can implement more than one interface (multiple interfaces). Let's take a tour with the following examples to understand the implementation of the interface. Example 1 This is a format of the interface.
public interface InterfaceName {
public String hello = "Hello";
public void sayHello();
}
As you can see at the given example, an interface is declared using the interface keyword. Just like with classes, a Java interface can be declared public or package scope; it does not use access specifier. The above example contains one variable and one method. In Java, the variable can be accessed directly from the interface, like this:
System.out.println(InterfaceName.hello);
Example 2
interface X
{
void m1();
void m2();
void m3();
void m4();}
abstract class Test2 implements X{
public void m3()
{
     System.out.println("In method m3");
     }}
class Test3 extends Test2{
public void m1(){System.out.println("In method m1");}
public void m2(){System.out.println("In method m2");}
public void m4(){ System.out.println("In method m4");
}}
public class Test1{
public static void main(String args[]){
X obj=new Test3();
obj.m1();
obj.m2();
obj.m3();
obj.m4();}
}
Output
In method m1
In method m2
In method m3
In method m4

Advantage of Abstraction

Some of the advantages of abstraction are as follows
  • It reduces view complexity of the class members.
  • It avoids duplication of code.
  • It increases the reusability of code.
  • It Increases the readability of the program if things are appropriately abstracted, then the reader does not retain everything.
  • It supports polymorphism.
  • It provides security.

Abstraction VS. Encapsulation

Both abstraction and interface are a major oops concept of Java. They allowed you to enhance the real world thing into an object so it can be implemented in the program. Many are got confused between abstraction and encapsulation because they are quite similar. Abstraction hides complexity while encapsulation hides internal working. Let’s have a look at some following differences.
1 Abstraction hides details at the design level. Encapsulation hides details at the implementation level.
2 Abstraction hides unwanted information for the user's dynamic view. Encapsulation hides the block of code. Wrap it into a single unit.
3 It uses the keyword abstract to make an abstract class for abstraction In encapsulation create a class variable as private.
4 Abstraction is created using abstract classes and interfaces. Provides setter and getter for accessing and modifying the data.
5 Abstraction is used for hiding the backend data. It wraps up data into a single unit.

Related Topics

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Factorial of a Large Number in Java

We've already talked about a number's factorial. We must still go over the factorial of a large number separately, though. The method used to determine the factorial of a small...

8 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.