Last active
August 29, 2015 14:04
-
-
Save kenorb/4daf7f169b8e147db1ca to your computer and use it in GitHub Desktop.
Final Keyword Demo in Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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