Sobes.tech
Junior — Middle

How can new features be added to an existing class?

sobes.tech AI

Answer from AI

In Java, adding new capabilities to an existing class can be done in several ways:

  • Inheritance: create a subclass that extends the functionality of the base class.
  • Composition: include an instance of an existing class in a new class and add new methods.
  • Using interfaces and default methods: starting from Java 8, interfaces can contain methods with implementations, allowing to add behavior.
  • Decorator Pattern: wrap an object of an existing class in another class that adds new capabilities.

Example of inheritance:

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

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

    void fetch() {
        System.out.println("Fetching ball");
    }
}

Thus, the Dog class extends the Animal class, adding new methods and changing behavior.

How can new features be added to an existing class… - sobes.tech