0% found this document useful (0 votes)
14 views1 page

Final Keyword Example

Uploaded by

prathamthor20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views1 page

Final Keyword Example

Uploaded by

prathamthor20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Final Keyword Examples

// Final class - cannot be subclassed


final class FinalClass {
// final variable - constant, value can’t change
final int MAX_SPEED = 120;

// final method - cannot be overridden by subclasses


final void display() {
System.out.println("This is a final method.");
}

void showSpeed() {
System.out.println("Max speed is: " + MAX_SPEED);
}
}

// Trying to extend FinalClass will cause an error


// class SubClass extends FinalClass {} // Error!

public class FinalKeywordDemo {

public static void main(String[] args) {


FinalClass obj = new FinalClass();

// Using final variable


System.out.println("MAX_SPEED = " + obj.MAX_SPEED);

// Trying to change final variable (will cause error)


// obj.MAX_SPEED = 150; // Error: cannot assign a value
to final variable

// Calling final method


obj.display();

// Calling normal method


obj.showSpeed();
}
}

You might also like