bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!
×
UPTO
50%
OFF!

final Keyword in Java

 

Keyword final is used along with:

  • Variables
  • Methods
  • Classes

 

final variables: If you use a variable as a final then the value of variable is become constant. You cannot change the value of a final variable once it is initialized.

e.g.

class Apple{

final int  quantity=10; // quantity as a final variable

void show(){

quantity=50;

}

public static void main(String args[]){

Apple ap=new  Apple ();

ap.show();

}

}

Output

Apple.java:4: error: cannot assign a value to final variable quantity

quantity=50;

^

1 error

So when you use final variable then you cannot change its value.

 

final Method: Final method cannot be overridden. That means a subclass can call a final method of parent class without any issues but it cannot override it.

e.g.

class Fruit{

final void show(){  // final method

System.out.println("Fruit class created");

}

}

 
class Apple extends Fruit{

void show(){

System.out.println("Apple class created");

}

public static void main(String args[]){

Apple ap = new Apple();

ap.show();

}

}

Output :

Apple.java:8: error: show() in Apple cannot override show() in Fruit

void show(){

^

overridden method is final

1 error

It will show error because method show is final so it cannot be overridden.

 

final Class:

If you make class as final then you cannot inherit that class that means you cannot extend it.

e.g.

final class Fruit{

……..

}

class Apple extends Fruit{

void show(){

System.out.println("Apple class created");

}

public static void main(String args[]){

Apple ap = new Apple();

ap.show();

}

}

Output

Apple.java:5: error: cannot inherit from final Fruit

public class Apple extends Fruit{

^

1 error

It will show error because class Fruit is final so it cannot be inherited.

Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

"0 Responses on final Keyword in Java"

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.
top

Sales Offer

  • To avail this offer, enroll before 18th November 2017.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer

Sign Up or Login to view the Free final Keyword in Java.