Tuesday, September 10, 2013

Selenium : Final Keyword

Selenium : Final Keyword

Final is different than finally keyword which is used on Exception handling in Java. 

Final variable 
  1. It must be initialized at the time of declaration or inside constructor. 
  2. Once you make a initialized final you are not allowed to change it and compiler will raise compilation error if you try to re-initialized final variables in java. 
  3. Final variables are often declare with static keyword in java and treated as constant. 

Example :
public static final String sVar = "some_Data";
sVar = "HI"; //invalid compilation error
sVar = new String("new_data"); //invalid compilation error

  final method
  1. Final keyword in java can also be applied to methods.
  2.  You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. 
  3. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time.
Example:
class Loan
 {
 public final String getName()
{
     return "personal loan";
 }
}
class PersonalLoan extends Loan
 {
    @Override
    public final String getName()
 {
        return "cheap personal loan"; //compilation error: overridden method is final
    }
}

  final Class in Java

  1.   Final class is complete in nature and can not be sub-classed or inherited. 
  2. Several classes in Java are final e.g. String, Integer and other wrapper classes. 
Example :
final class Loan
 {
}
class PersonalLoan extends Loan 
{  //compilation error: cannot inherit from final class
 
}

Benefits of final keyword in Java

1. Final keyword improves performance.
2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.

 

2 comments:

  1. Totally cool and fantastic photo manipulation art work.

    PIC Bonus

    ReplyDelete
  2. Your article is very helpful to people who want to learn Java Language. You explained the use of Final keyword very well. Final keyword is used in many places. If we use final keyword with a variable it will treated as constant, and If we use final keyword with method then it can’t be override, and If we use final with class, means we can’t inherit that final class. I also have a blog(Java2Blog) which provides complete Java tutorial for beginners.

    ReplyDelete