Sobes.tech
Junior

What is the principle of abstraction?

sobes.tech AI

Answer from AI

The principle of abstraction allows hiding implementation details and presenting only the essential characteristics of an object or system.

In Java, abstraction is implemented using:

  1. Abstract classes (abstract class):

    • Can contain abstract methods (without implementation) and concrete methods.
    • Cannot be instantiated directly.
    • Used to define a common base for subclasses.
    // Abstract class Shape
    abstract class Shape {
        // Abstract method for calculating area
        abstract double calculateArea();
    
        // Concrete method
        public void displayMessage() {
            System.out.println("This is a geometric figure.");
        }
    }
    
  2. Interfaces (interface):

    • Contain only abstract methods (before Java 8).
    • Define a contract that must be implemented by classes.
    • Allow achieving multiple inheritance of behavior.
    // Interface Drawable
    interface Drawable {
        // Abstract method for drawing
        void draw();
    }
    

Applying abstraction simplifies working with complex systems, allowing focus on high-level logic without getting distracted by low-level details. This increases flexibility, modularity, and ease of maintenance of the code.

What is the principle of abstraction? — Java - sobes.tech