Sobes.tech
Junior

How can you describe abstraction in programming?

sobes.tech AI

Answer from AI

Abstraction is a principle of hiding complexity, highlighting only the essential characteristics of an object or system, and ignoring secondary details. In Java, abstraction is implemented using:

  • Abstract classes (abstract class): Cannot be instantiated directly, can have abstract and concrete methods, and provide a basic functionality and structure for subclasses.
    // Abstract class Shape
    abstract class Shape {
        // Abstract method to calculate area
        abstract double calculateArea();
    
        // Concrete method
        void display() {
            System.out.println("This is a shape.");
        }
    }
    
  • Interfaces (interface): Define a contract consisting of a set of abstract methods (before Java 8), static, and default methods (Java 8+). They do not contain state (except static and default methods in Java 8+).
    // Interface Drawable
    interface Drawable {
        // Abstract method for drawing
        void draw();
    
        // Default method (Java 8+)
        default void printDescription() {
            System.out.println("This is a drawable object.");
        }
    }
    

Abstraction allows:

  • Simplifying the understanding and use of complex systems.
  • Focusing on what the object does, rather than how it does it.
  • Providing flexibility and the ability to change internal implementation without affecting external usage.
  • Creating class hierarchies where abstract classes or interfaces define common structure and behavior.

Example of usage:

// Implementation of abstract class Shape
class Circle extends Shape {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    // Implementation of abstract method
    @Override
    double calculateArea() {
        return Math.PI * radius * radius;
    }
}

// Implementation of interface Drawable
class Square implements Drawable {
    private double side;

    Square(double side) {
        this.side = side;
    }

    // Implementation of interface's abstract method
    @Override
    public void draw() {
        System.out.println("Drawing a square with side " + side);
    }
}

// Using abstractions
public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle(5.0);
        System.out.println("Circle area: " + circle.calculateArea()); // Calling abstract method via reference to abstract class

        Drawable square = new Square(4.0);
        square.draw(); // Calling abstract method via reference to interface
        square.printDescription(); // Calling default method of interface
    }
}