Skip to content

Instantly share code, notes, and snippets.

@kenorb
Last active August 29, 2015 14:04
Show Gist options
  • Save kenorb/4daf7f169b8e147db1ca to your computer and use it in GitHub Desktop.
Save kenorb/4daf7f169b8e147db1ca to your computer and use it in GitHub Desktop.
Final Keyword Demo in Java.
/*
* Final Keyword Demo.
*
* This demo will generate 3 errors:
* - error: cannot inherit from final A
* - error: display() in B cannot override display() in A
* - error: cannot assign a value to final variable x
*
* Uses of final keyword can be used:
* - to prevent inheritance;
* - to prevent method overriding;
* - to declare the constant variables;
*
* How to run:
* javac FinalDemo.java
* java B
*/
final class A {
final void display() {
}
}
class B extends A { // Error: A final class cannot be extended.
void display() { // Error: Final method cannot be overridden.
final int x = 1000;
x = 2000; // Error: A final variable cannot be modified.
}
}
class C extends B {
int x = 3000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment