final methods and final classes
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)final means "this cannot be changed". On a method, it stops a child class from writing its own version of that method. On a class, it stops anyone from extending the class at all.
One word, three places
You know final on variables from final variables (opens in a new tab): the value cannot change once set. With inheritance, final gets two more jobs, on methods and on classes.
class Loan { final int maxAmount = 500000;
final int interest() { return 8; }}
final class PanCard { String number;}Read the three uses:
- A
finalvariable,maxAmount, cannot get a new value. - A
finalmethod,interest(), cannot be replaced by a child class. - A
finalclass,PanCard, cannot be extended at all.
final methods
A final method is a method declared with final. A child class inherits it and can call it, but cannot override it, that is, cannot write its own version with the same name and parameters.
Every kind of loan must use the same interest formula. Mark the method final: a child still inherits it and can call it, but cannot write its own method with the same name and parameters.
Example 1 · A child can call a final method
class Loan { int amount;
final int interest() { return amount * 10 / 100; }}
class HomeLoan extends Loan { void showEmiInfo() { System.out.println("Loan: Rs. " + amount); System.out.println("Interest: Rs. " + interest()); }}
public class FinalMethodDemo { public static void main(String[] args) { HomeLoan h = new HomeLoan(); h.amount = 500000; h.showEmiInfo(); }}Loan: Rs. 500000 Interest: Rs. 50000
What this code does
interest()is final, butHomeLoanstill inherits it and calls it like any other method.- Every kind of loan uses the same formula, because no child can replace it.
Example 2 · Mistake: a child writes its own version of a final method
class Loan { int amount;
final int interest() { return amount * 10 / 100; }}
class HomeLoan extends Loan { int interest() { return 0; }}
public class FinalMethodErrorDemo { public static void main(String[] args) { HomeLoan h = new HomeLoan(); h.amount = 500000; System.out.println(h.interest()); }}FinalMethodErrorDemo.java:10: error: interest() in HomeLoan cannot override interest() in Loan
int interest() {
^
overridden method is final
1 errorWhat this code does
HomeLoantries to write its owninterest()with the same name and parameters. That is overriding, andfinalforbids it.- Read the error as: "
HomeLoanmay not replaceLoan'sinterest(), because it is final".
Writing your own version of a parent's method is called overriding. Normal methods allow it; Method overriding (opens in a new tab) in the next module shows how and why. final on a method switches it off.
final classes
A final class is a class declared with final. It cannot be extended, so no class can be its child; String and Math are final classes.
Nobody should be able to make a fake child of PanCard. Write final class PanCard: a final class can have no children at all, so none of its methods can ever be replaced.
Example 3 · Your own final class
final class PanCard { private final String number;
PanCard(String number) { this.number = number; }
String getNumber() { return number; }}
class FakePanCard extends PanCard { FakePanCard() { super("FAKE00000X"); }}
public class FinalClassDemo { public static void main(String[] args) { System.out.println(new PanCard("ABCDE1234F").getNumber()); }}FinalClassDemo.java:13: error: cannot inherit from final PanCard
class FakePanCard extends PanCard {
^
1 errorWhat this code does
PanCardis final, soFakePanCardcannot extend it, even with a correct constructor.- Remove
FakePanCardand the program compiles: a final class works normally, it just has no children.
Example 4 · String is a final class
class MyString extends String {}
public class FinalStringDemo { public static void main(String[] args) { System.out.println("Hello"); }}FinalStringDemo.java:1: error: cannot inherit from final String
class MyString extends String {
^
1 errorWhat this code does
Stringis declaredfinalin Java, so no class can extend it.- Every
Stringin every program behaves exactly the same way.
Java's own String and Math classes are final. Strings carry names, passwords and file paths everywhere; if anyone could make a child of String that behaved differently, no code could trust the strings it gets.
Find the bug
Find the final mistake
Select the line that is wrong.
PanCard is final on purpose. This file should compile.
Round 1 of 4What final on a class does not mean
DebitCard is final, yet it extends Card and its balance changes with every spend. A final class can still have a parent, and its objects are not frozen: only final fields stay fixed.
Example 5 · A final class can have a parent, and its objects can change
class Card { String holder;}
final class DebitCard extends Card { int balance;
void spend(int amount) { balance = balance - amount; System.out.println(holder + " spent Rs. " + amount + ", left Rs. " + balance); }}
public class FinalObjectDemo { public static void main(String[] args) { DebitCard d = new DebitCard(); d.holder = "Kavya"; d.balance = 2000; d.spend(450); d.spend(300); }}Kavya spent Rs. 450, left Rs. 1550 Kavya spent Rs. 300, left Rs. 1250
What this code does
DebitCardis final but still extendsCardand uses the inheritedholder.balancechanges freely:finalon the class blocks children, not changes to fields.
Use final on a class when it is complete and must not be changed by children; leave a class open when others should extend it. Objects that never change are built in Immutable objects (opens in a new tab).
Next step
Check your understanding
11 quick questions