Sobes.tech
Junior — Middle

What language constructs or object-oriented programming mechanisms are implemented in this code example?

sobes.tech AI

Answer from AI

In Java, the following key constructs and mechanisms are used to implement object-oriented programming (OOP):

  • Classes and objects — the foundation of OOP, classes describe the structure and behavior of objects.
  • Inheritance — allows creating a new class based on an existing one, extending or overriding its functionality.
  • Encapsulation — hiding the internal implementation of a class, usually through access modifiers (private, protected, public).
  • Polymorphism — the ability to use objects of different classes through a common interface, for example, through method overriding.

Example:

public class Animal {
    public void sound() {
        System.out.println("Some sound");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.sound(); // Outputs "Bark" — an example of polymorphism
    }
}

This example demonstrates inheritance (Dog extends Animal), method overriding (sound), and polymorphism (calling a method through a reference to the base class).

What language constructs or object-oriented… - sobes.tech