Some more concept about final

Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:
  1. class Bike{  
  2.   final void run(){System.out.println("running...");}  
  3. }  
  4. class Honda2 extends Bike{  
  5.    public static void main(String args[]){  
  6.     new Honda2().run();  
  7.    }  
  8. }  
Output: running...

What is blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.

Example of blank final variable

  1. class Student{  
  2. int id;  
  3. String name;  
  4. final String PAN_CARD_NUMBER;  
  5. ...  
Que) Can we initialize blank final variable?
Yes, but only in constructor. For example:
  1. class Bike10{  
  2.   final int speedlimit;//blank final variable  
  3.     
  4.   Bike10(){  
  5.   speedlimit=70;  
  6.   System.out.println(speedlimit);  
  7.   }  
  8.   
  9.   public static void main(String args[]){  
  10.     new Bike10();  
  11.  }  
  12. }  
Output: 70

Static blank final variable

A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.

Example of static blank final variable

  1. class A{  
  2.   static final int data;//static blank final variable  
  3.   static{ data=50;}  
  4.   public static void main(String args[]){  
  5.     System.out.println(A.data);  
  6.  }  
  7. }  

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.
  1. class Bike11{  
  2.   int cube(final int n){  
  3.    n=n+2;//can't be changed as n is final  
  4.    n*n*n;  
  5.   }  
  6.   public static void main(String args[]){  
  7.     Bike11 b=new Bike11();  
  8.     b.cube(5);  
  9.  }  
  10. }  
Output: Compile Time Error

Q) Can we declare a constructor final?

No, because constructor is never inherited.





Comments

Popular posts from this blog

Handling Dynamic Web Tables Using Selenium WebDriver

Verify Specific Position of an Element

Read it out for TESTNG before going for an iterview