Saturday, 11 April 2020

Final Keyword with Inheritance-Java

The final is a keyword in java used with variable, methods, and classes to restrict some of their features. In java the final keyword is most useful in the context of inheritance. How you are used both super and this key with classes and methods similarly final is also used.

In java there are three uses of final keyword:
  1. To define symbolic constant 
  2. To prevent method overriding
  3. To prevent a class to inherit.

1. Final Variable in Java

A variable which is declared using final is called a final variable or symbolic constants. Like C program how you are using "const" keyword to declare constants, in java final keyword is used.

syntax: final type variable-name=value;
Example: final int a=10;

Final variables must be declared at the type of their deceleration.If you can't initialized it then it is called " blank final variable". Variables such as Aadhar Number and PAN CARD number ext.. are initialized only once and this can be done using constructor of that class.  

2. To prevent method overriding

If you want a super class method can't be override in its sub classes, then declare that super class method as final. For example
class A 
{
   final void display()    
    {
       System.out.println(" I am super class method");    
    } 
}
class B extends A 
{
     void display()      
  { super.display();                
  System.out.println(" I am sub class method");       
  } 
}
class FinalOverridingDemo
{
public static void mian(String args[]) 
 {
         B  b1=new B();             
   b1.display();             
}
}



The program will generate an error " final method can't be Overridden". Below is the output check it

3. To prevent inheritance

If you wish to stop inheriting a class by its sub classes, then declare that class as final class. A class that is declared using final variable is called final class. For example, consider the following program.
  final class A 
{
  void display()    
    {
       System.out.println(" I am super class method");    
    } 
}
class B extends A 
{
     void display()      
  { super.display();                
  System.out.println(" I am sub class method");       
  } 
}
class FinalClassDemo
{
public static void mian(String args[]) 
 {
         B  b1=new B();             
   b1.display();             
}
}

It will generate an error" final class can't be inherit"..check below out put


Q) Is final method inherited?
 
Ans) Yes, final method is inherited but you cannot override it.
 

Q) Can we declare a constructor final?

No, because constructor is never inherited.

0 comments:

Post a comment

Find Us On Facebook

Contact Us

Name

Email *

Message *

C Programming

More

C++ Tutorial

More

Java Tutorial

More

software engineering

More

MS Office

More

Database Management

More

Advertisement

Top