Prevent a class from being extended

  • When you define a class, you can control whether your class can be used as a super class

  • Suppose you do not want your class to be used as a super class

    • How can you stop Java from using your class as super class ?


  • A class with the final qualifier cannot be extended (i.e., used as a superclass)

    Example:

    /* ======================================
       This class cannot be extended
       ====================================== */
    public final class myClass 
    {
    
       // Data fields, constructors, and methods omitted
    
    } 

DEMO: demo/04-inheritance/23-final-class/Circle.java + GeometricObject.java

Prevent a (inherited) method from being overridden

  • Suppose you define a class that will be used as a super class, but you do not allow some method(s) in the class to be overriden

    • How can you stop some program from overriding your methods after inheriting from your class ?

  • A method with the final qualifier cannot be overridden in a subclass:

    public class myClass  // Class can be used as super class
    {
        ....
    
        /* =============================================
           But: this method cannot be overridden
           ============================================= */
        public final void method1()
        {
            // Do something
        }
    
        ....
    } 

DEMO: demo/04-inheritance/23-final-method