Final Classes Tutorial

When the final keyword is applied to a class, the final class cannot be extended. In other words, a final class can never be the superclass of a subclass. A final class can be the subclass of superclass, not problem there. When a class is marked final, all of its methods are implicitly final as well. In this tutorial, I will reuse the source code from my Final Methods Tutorial. I will explore the benefits and ramifications of marking the Commission class final.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md FinalClasses
C:\Java>cd FinalClasses
C:\Java\FinalClasses>Notepad FinalClasses.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class FinalClasses {
    public static void main(String args[]) {
        double totalPrice = 100.00D;
        // SalesPerson person = new SalesPerson("Bob", totalPrice); 
        // System.out.println(person.getName() + " made $" + person.getPayout() + " commission on a sale of $" + totalPrice );

        Commission pay = new Commission(totalPrice); // we can still create an object instance of a final class
        System.out.println("Bob made $" + pay.getPayout() + " commission on a sale of $" + totalPrice );
    }
}

final class Commission {
    private double payout = 0.0D;
    
    Commission() {
        super();
    }

    Commission(double salesPrice) {  
        payout = calculatePayout(salesPrice);
    }

    double calculatePayout(double salesPrice) { // implicity final
        return salesPrice * .3275; // 32.75% payout to sales person
    }

    double getPayout() { // implicitly final
        return payout;
    }
}


/* class SalesPerson extends Commission { // Can't extend Commission because of final
    private String name = "";
    SalesPerson() {
        super();
    }
    SalesPerson(String name, double salesPrice) {
        super(salesPrice);
        this.name = name;
    }

    //@Override
    //double calculatePayout(double salesPrice) { // implicity final
    //   return salesPrice * .4275; // 42.75% payout to sales person
    //}

    String getName() {
        return name;
    }
}*/


Now switch back to the command prompt (CMD) and type in javac FinalClasses.java and press Enter.
Now type in java FinalClasses and press Enter.


C:\Java\FinalClasses>javac FinalClasses.java
C:\Java\FinalClasses>java FinalClasses
Bob made a $32.75 commission on a sale of $100.0


Final thoughts

Marking a class final can ensure better security. However, the cost of doing so eliminates object-oriented inheritance. There are many classes in the core Java class libraries that are marked final. The String class is a well known final class.


Tutorials