Java-Final to Prevent Overriding

Final to Prevent Overriding

All methods and variables can be overridden by default in subclasses. If we wish to prevent the subclasses from overriding the members of the superclass, we can declare them as final using the keyword final as a modifier. If any attempt to override a final method in a subclass results in the compiler error. For example, in the following program, the method dataValues( ) is declared as final, it cannot be overridden in DataV2. If you attempt to do so, a compile error will result.

Program

Program Source

class DataV1 {
    
    final void dataValues()
    {
        System.out.println("DataV1 Values");
    }
}

class DataV2 extends DataV1{
    
    void dataValues()
    {
        System.out.println("DataV2 Values");
    }
}

public class Javaapp {
    
    public static void main(String[] args){
        
        DataV2 obj = new DataV2();
        obj.dataValues();
   }
}

Leave a Comment