Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Final Method

Posted By: Lucinda Hall     Category: Java     Views: 12848

This article explains about final method in java with example.

Final methods are those which can not be overridden by a subclass. 

Syntax of Final Method

class clsName
{
     // Variable declaration
 
     // Constructor

     // Method
     final rtype mthName(params)
     {
          // Body of final method
     }
}

clsName is a valid identifier in java. It is a class name.
final is a keyword to declare that method final.
rtype is return type of a method.
mthName is a method name and valid java identifier.

Example of Final Method

Example 1 : Program that illustrates the use of final method

abstract class Shape
{
      public static float pi = 3.142f; 
      protected float height;
      protected float width;

      abstract float area() ;
}  

class Square extends Shape
{
      Square(float h, float w)
      {
             height = h;
             width = w;
      }

      final float area() // This method cannot be overridden in it's sub classes
      {
            return height * width;
       }
}

class Rectangle extends Shape
{
      Rectangle(float h, float w)
      {
             height = h;
             width = w;
      }

      final float area()  // This method cannot be overridden in it's sub classes
      {
             return height * width;
      }
}

class Circle extends Shape
{
      float radius;

      Circle(float r)
      {
             radius = r;
      }

      final float area()  // This method cannot be overridden in it's sub classes
      {
            return Shape.pi * radius *radius;
      }
}

class FinalMethodDemo
{
        public static void main(String args[])
        {
                 Square sObj = new Square(5,5);
                 Rectangle rObj = new Rectangle(5,7);
                 Circle cObj = new Circle(2);

                 System.out.println("Area of square : " + sObj.area());
                 System.out.println("Area of rectangle : " + rObj.area());
                 System.out.println("Area of circle : " + cObj.area());
        }
}

Output
Area of square : 25
Area of rectangle : 35
Area of circle : 12.568
  
Share: 

 
 
 

Didn't find what you were looking for? Find more on Final Method Or get search suggestion and latest updates.

Lucinda Hall
Lucinda Hall author of Final Method is from Los Angeles, United States.
 
View All Articles

Related Articles and Code:


 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!