Sobes.tech
Junior — Middle

Can you explain the principles of object-oriented programming and how they are implemented in modern languages?

sobes.tech AI

Answer from AI

Object-oriented programming (OOP) is based on four main principles:

  1. Encapsulation — combining data and methods that operate on that data into a single object. This allows hiding internal implementation details and protecting data from direct external access.

  2. Inheritance — a mechanism that allows creating new classes based on existing ones, inheriting their properties and methods, which promotes code reuse.

  3. Polymorphism — the ability of objects of different classes to respond to the same messages (method calls) in different ways, usually through method overriding.

  4. Abstraction — highlighting the essential characteristics of an object, hiding implementation details, which simplifies interaction with the object.

In modern programming languages like Java, these principles are implemented as follows:

  • Classes and objects implement encapsulation using access modifiers (private, protected, public).
  • Inheritance is achieved through the extends keyword.
  • Polymorphism is implemented through method overriding and interfaces.
  • Abstraction is supported via abstract classes and interfaces.

Example in Java:

abstract class Animal {
    abstract void sound();
}

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

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

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

This demonstrates inheritance, polymorphism, and abstraction.