Java - Method Overriding

Introduction

In this blog, I will explain about the Method Overriding concept in Java. It is very simple in Java programming. The output will be displayed in the Run module.

Software Requirement

JDK1.3.

Overriding

The benefit of overriding is the ability to define a behavior, which is specific to the subclass type, which means a subclass can implement a parent class method, based on its requirement. In object-oriented terms, overriding means to override the functionality of an existing method.

Simple program

  1. class circle  
  2.  {  
  3.  double r;  
  4.   
  5.  circle()  
  6.   {  
  7.      r = 10;  
  8.   }  
  9.   
  10.   void getarea()  
  11.     {  
  12.        double a;  
  13.        a = (3.14 * r *r);  
  14.        System.out.println("\nArea of Circle is : " + a);  
  15.     }  
  16.  }  
  17.        
  18. class cylinder extends circle  
  19.  {  
  20.    double r,h;  
  21.      
  22.    cylinder(double rad, double height)  
  23.      {  
  24.        r = rad;  
  25.        h = height;   
  26.      }  
  27.   
  28.     void getarea()  
  29.       {  
  30.          double a;  
  31.          a = (3.14*r*r*h);   
  32.          System.out.println("\nArea of Cylinder is : " + a);  
  33.       }  
  34.   }  
  35.   
  36. class area  
  37.  {  
  38.    public static void main(String arg[])  
  39.      {  
  40.         circle c = new circle();  
  41.         cylinder l = new cylinder(5,10);  
  42.         circle re;  
  43.   
  44.         re = c;  
  45.         re.getarea();  
  46.   
  47.         re = l;  
  48.         re.getarea();  
  49.      }            
  50.   } 
Explanation

In this blog, I explained about Method Overriding concept in Java programming. The output will be displayed in the Run module.

Output

Ebook Download
View all
Learn
View all