Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (we will not cover this topic).
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
Animal.java
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // will generate an error
To access the abstract class, it must be inherited from another class.
Cat.java
// Subclass (inherit from Animal)
class Cat extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The cat says: miaw miaw");
}
}
TestCat.java
class TestCat {
public static void main(String[] args) {
Cat myCat = new Cat(); // Create a Cat object
myCat.animalSound();
myCat.sleep();
}
}
The output will be:
The cat says: miaw miaw
Zzz
To achieve security - hide certain details and only show the important details of an object.