Program to implement Method Overriding for following inheritance

When a superclass and subclass both have a method having same name and same type signatures (same return type and number of arguments with same data types) then the method in the subclass is said to be override the method of superclass.

In this program area( ) is a method of superclass Shape which have same method name, same return type and no arguments is overridden in subclasses Rectangle and Triangle. When a overridden method is called from within a subclass then it always calls the method in subclass, whereas the method defined in superclass will be hidden.

An abstract class is a class that cannot be instantiated. When a method is declared as "abstract" in a class it must be overridden by the subclass of the super classes which contain that method. An abstract method does not have body. Body of an abstract method will be defined by subclass. To declare an abstract method use the following form:
abstract   return-type   <method-name> (parameter-list);

Any class that contains one or more abstract methods must also be declared as abstract. That is, an abstract class cannot be directly instantiated with the new operator.
abstract  class  <class-name> {

 // abstract method
 abstract  return-type  <method-name>( );
 // concrete or non-abstract method
 return-type  <method-name>( );

import java.lang.*;

abstract class Shape {
 int dim1,dim2;
 void getd()throws IOException {
  BufferedReader br = new BufferedReader (new InputStreamReader(;
  System.out.println ("Enter Value of 1st Dimension");
  System.out.println ("Enter Value of 2nd Dimension");
 abstract void area();

class Rectangle extends Shape {
 void getd() throws IOException {
 void area() {
  int a=dim1*dim2;
  System.out.println ("Area of Rectangle = "+a);

class Triangle extends Shape
 void getd() throws IOException {
 void area() {
  double b=(1*dim1*dim2)/2;
  System.out.println ("Area of Triangle = "+b);

public class MethodOverriding {

 public static void main(String[] args) throws IOException {
  Rectangle R = new Rectangle();
  Triangle T = new Triangle();
C:\>java MethodOverriding
Enter Value of 1st Dimension
Enter Value of 2nd Dimension
Area of Rectangle = 504
Enter Value of 1st Dimension
Enter Value of 2nd Dimension
Area of Triangle = 598.0

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative