Java Abstraction
Data Abstraction in Java is the process of hiding certain details and showing only essential information to the user.
Java Abstract Classes and Methods
Abstraction in Java can be achieved using the abstract classes and interfaces. The abstract keyword is a non-access modifier, used for classes and methods:
Note: The abstract class can have both abstract method and normal method.
Example:
abstract class AnimalSound { public void sleep(){ System.out.println("Zzzzz"); } public abstract void animalSound(); }
From the above example, it is not possible to create object for the class AnimalSound . The below code throws an error:
AnimalSound myAnimal = new AnimalSound();
The following error has been generated:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot instantiate the type AnimalSound
at practices.AnimalSoundClass.main(AnimalSoundClass.java:5)
To access the Abstract class, it should be inherited to its sub class. We use extend keyword to inherit from the Abstract class as well.
Example
AnimalSound.java
abstract class AnimalSound { public void sleep(){ System.out.println("Zzzzz"); } public abstract void animalSound(); } class Dog extends AnimalSound{ public void animalSound(){ System.out.println("Dog makes bow bow sound"); } } class Cat extends AnimalSound{ public void animalSound(){ System.out.println("Cat makes meow meow sound"); } } class Cow extends AnimalSound{ public void animalSound(){ System.out.println("Cow makes moo moo sound"); } }
AnimalSoundClass.java
public class AnimalSoundClass { public static void main(String args[]){ AnimalSound myDog = new Dog(); AnimalSound myCat = new Cat(); AnimalSound myCow = new Cow(); myDog.animalSound(); myCat.animalSound(); myCow.animalSound(); myDog.sleep(); //Accessing the abstract class "Regular method" } }
Output
Dog makes bow bow sound Cat makes meow meow sound Cow makes moo moo sound Zzzzz
Why use Abstract class and methods?
Through Abstract class and methods, we achieve security of the code and show only the important details of an object. Data Abstraction can also be achieved through Interfaces.