Java Tutorials
Java Methods
Java Classes
Java File Handling
Data abstraction is the process of hiding certain information and displaying only the information that is important to the user.
Abstract can be achieved through abstract classes or interaces (which you will learn more about in the next chapter).
abstract
keyword is an inaccessible fixer, used for classes and methods:
Invisible class may have subtle and general modes:
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 Animal category item:
Animal myObj = new Animal(); // will generate an error
To achieve an abstract class, it must be achieved in another class. Let's turn the Animal category we used in the Polymorphism chapter into an invisible category:
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
For security - hide certain details and show only important details of the item.
Note: Abstraction can also be gained through Interfaces, which you will learn more about in the next chapter.