DEV Community

Tamilselvan K
Tamilselvan K

Posted on • Edited on

Day-68 Understanding Abstraction in Java

What is Abstraction?

Abstraction is the process of hiding unwanted or unnecessary information and showing only the essential details to the user.

It helps reduce complexity and allows the programmer to focus on interactions rather than internal implementation.

Abstraction in Java

Java uses two main features to achieve abstraction:

  • Abstract Classes
  • Abstract Methods

Abstract Method:

  • A method without a body.
  • Declared using the abstract keyword.
  • Must be overridden in a subclass.

Abstract Class:

  • Cannot be instantiated directly(we cannot create object).
  • Can contain both abstract and non-abstract methods.
  • Used as a base class for other classes.

Object Creation:

  • Objects cannot be created directly from an abstract class.
  • A child class must extend the abstract class and provide implementations for all abstract methods.

Illegal Combinations:

  • The use of static and abstract together in the same method is not allowed.
  • This is because abstract requires method overriding, while static restricts it.

Example

public abstract class Mother {

    public Mother() {
        System.out.println("Mother-const"); // Constructor in abstract class
    }

    public static void main(String[] args) {
        // Mother mother = new Mother();  // Error: cannot instantiate abstract class
        // mother.workHard();
        // mother.motivate();
    }

    public abstract void study(); // Abstract method (no body)

    public void workHard() {
        System.out.println("workHard"); // Regular method
    }

    public void motivate() {
        System.out.println("Motivate");
    }
}
Enter fullscreen mode Exit fullscreen mode
public class Son extends Mother {

    public static void main(String[] args) {
        Son son = new Son();       // Object created in child class
        son.study();               // Calls overridden method
        son.workHard();            // Inherited method
        son.motivate();            // Inherited method
    }

    public void study() {
        System.out.println("BE"); // Body provided by subclass
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Mother-const
BE
workHard
Motivate
Enter fullscreen mode Exit fullscreen mode

Top comments (0)