Final Methods Tutorial

The keyword final can be applied to many things, in the next few tutorials I will explore how it affects the behavior of methods, classes, and variables. There are some slight key differences in the functionality of the final keyword with respect to what you are applying it to. When the keyword final is applied to methods, it will prevent a method from being overridden in a subclass. The method will still be inherited; it just simply cannot be overridden. Applying final to a method is common when a method is called from a constructor and you want to ensure that its functionality cannot be changed when used in future subclasses.



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 FinalMethods
C:\Java>cd FinalMethods
C:\Java\FinalMethods>Notepad FinalMethods.java

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


class FinalMethods {
    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 );
    }
}

class Commission {
    private double payout = 0.0D;

    Commission() {
        super();
    }

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

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

    double getPayout() {
        return payout;
    }
}


class SalesPerson extends Commission {
    private String name = "";

    SalesPerson() {
        super();
    }

    SalesPerson(String name, double salesPrice) {
        super(salesPrice);
        this.name = name;
    }

    String getName() {
        return name;
    }
}



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


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


Final thoughts

Sometimes when you create a class, it doesn't even cross your mind that someone else may extend your class in the future. The ability to understand when to apply the final keyword to a method is a skill that just takes time and experience to master.


Tutorials