You can use final keyword with variables, methods and classes in Java. You can use final modifier with variables to make them constant. A final variable is initialized only once in its lifetime, once initialized you cannot change its value. Though, you can initialize final variable at the time you declare them or you can initialize them at constructor, if they are blank final variable. A static final variable, also known as constant must be initialized in the same line. You can also use final modifier with methods to prevent method overriding. In Java, you cannot override final methods. This is usually done to signal that method is complete and its not designed for extension. It is also done to prevent someone deliberately or accidentally changing core logic of method by overriding it e.g. in template design pattern, the method which keeps the algorithm, also known as template method should be final, because outline of algorithm should be changed by child classes. You can also use final keyword with classes to make sure they are not extensible. In Java, you can not extend a final class to create sub-classes. Why you make a class final? doesn't it take your right of code reuse via Inheritance and extending its functionality? This is usually done to protect the class' invariant e.g. due security reasons. This is why String is also made final in Java. If you are beginner, just started learning Java, I suggest you to refer at-least one book alongside your research and practice. That will make you progress more in less time. One of the good Java book for beginner is Cay. S. Horstmann's Core Java Volume 1 and 2, which is both readable, easy to understand and comprehensive enough to learn Java in deep.
Read more »
No comments:
Post a Comment