Monday, 28 November 2016

Program to demonstrate use of hierarchical inheritance using interface

This is simple program for hierarchical inheritance using interface. Here an interface Area is created having data member pi and method compute(float, float). After that two classes are created Rectangle and Circle. In these classes we have implemented Area interface and override the compute(float, float) method as shown in program.


PROGRAM
interface Area {
 
 final static float pi=3.14f;
 float compute(float x,float y);
}

class Rectangle implements Area {
 
 public float compute(float x,float y) {
  
  return(x*y);
 }
}

class Circle implements Area {
 
 public float compute(float x,float y) {
  
  return(pi*x*y);
 }
}

public class InterfaceTest {
 
 public static void main (String[] args) {
  
  Rectangle rect = new Rectangle();
  Circle cir = new Circle();
  Area area;
  area = rect;
  System.out.println("Area of Recatngle = "+area.compute(10,20));
  area = cir;
  System.out.println("Area of Circle = "+area.compute(10,10));
 }
}
OUTPUT
C:\>javac InterfaceTest.java
C:\>java InterfaceTest
Area of Recatngle = 200.0
Area of Circle = 314.0

No comments:

Post a Comment