Why we use Final Keyword ?
We can use “Final” with a variable, Method or Class
Final variable :-
In the below code we have declared WebDriver as Final but why??
Lets understand what is meaning of Final Keyword first!!
- Final Variable, is nothing but a constant(driver would act as constant above), as we cannot change its value once it is initialized.
- We need to initialize the value of final variable at the time of declaration,(like final int itest = 10;).We have a exception that we can have final variable uninitialized(blank Final Variable) but than it must be initialized inside a Constructor (i.e this.driver = driver 😉 the way it is done in our example scenario above.
Now in our example scenario, we have taken webdriver variable as final, so that one’s its value is initialized to the current webdriver instance we don’t want it to change.
1.We cannot override a final method.
Example:- We have taken TestClassA and TestClassB, where B Extends A, now incase we try to override the method of A in B.
2.But an subclass can call the final method of parent class but not override.Example we can call the add() method below using TestClassB object
1.We cannot extend a final Class
Example:- We have made our TestClassA as Final , and we cannot extend this class in TestClassB.
1.All variables inside an Interface are by default treated as final.
2.We need to initialize the final variable value while declaration other option is to initialize it inside a constructor.
3.We cannot override final method.
4.We cannot inherit final class.
5.We cannot declare constructor as final.