Sobes.tech
Junior — Middle

How can class extension be limited through inheritance?

sobes.tech AI

Answer from AI

You can restrict class extension through inheritance in the following ways:

  1. Declare the class as final (in languages that support this, such as Java) — such a class cannot be inherited.
public final class MyClass {
    // class body
}
  1. Make the class constructors private or protected and provide only static methods or factory methods — this way, the class cannot be inherited from outside.

  2. In some languages (e.g., C#), use the sealed keyword to prevent inheritance.

  3. Use composition instead of inheritance — if you need to limit extension, you can design the system so that classes are not inherited but use other classes as components.

In testing (QA), this is important to ensure that the class behavior does not change through inheritance, which could affect test stability.