Home / Questions / How can you ensure that a class cannot be inherited by other classes?
Explanatory Question

How can you ensure that a class cannot be inherited by other classes?

👁 222 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

What modifier can be used to prevent a class from being inherited?

This can be achieved by using the final modifier, as exemplified in the provided code snippet showcasing the Attribute class. This modifier prevents any further extension of the class, making it impossible for other classes to inherit its properties and methods. In the context of the code, the Attribute class is declared as final, which means that no other class can be derived from it, preserving its integrity and preventing unintended modifications through inheritance.

Preventing class inheritance

You can prevent classes from being inherited by using the final modifier.


public final class Attribute
{
    int objectField;
}