Java Abstraction


Abstract Classes and Methods

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:

  • Abstract class: is a limited category that can be used to create things (to achieve that, you must achieve another category).
  • Abstract method: can only be used in the invisible class, and it has no body. The body is provided by a subclass (inherited).

Invisible class may have subtle and general modes:


Example
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:


Example
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:


Example
// 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();
              }
            }
            

Why And When To Use Abstract Classes and Methods?

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.