Sobes.tech
Junior — Middle

Could you give an example of using abstraction in programming?

sobes.tech AI

Answer from AI

Abstraction in programming is the process of highlighting common characteristics of objects and hiding implementation details. It allows working with objects through their interfaces without delving into the details.

Example in Java:

// Abstract class
abstract class Animal {
    abstract void makeSound();
}

// Concrete class
class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Woof");
    }
}

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Meow");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        Animal cat = new Cat();
        dog.makeSound(); // Woof
        cat.makeSound(); // Meow
    }
}

Here, the Animal class defines an abstract method makeSound(), and the specific classes implement it in their own way. This allows working with different animals through a common interface.