Friday, 25 November 2016

Program to do the following Hierarchical Inheritance

In Hierarchical Inheritance there is one super class with many subclasses. Here, we have created one superclass Shape2 which is declared as abstract because of one abstract method area( ). This superclass is get inherited into two subclasses, Rectangle2 and Triangle2 which then override this area( ) method independently and do there own implementation in it.

You cannot create an object of abstract class but you can create a reference of it as shown below.


PROGRAM
abstract class Shape2 {
 
 abstract void area();   
}

class Rectangle2 extends Shape2 {
 
 int length, breadth;
  Rectangle2(int l, int b) {
  
  length = l;
  breadth = b;
 }
 
 public void area() {
  
  System.out.println("Area of Rectangle : "+ (length * breadth));
 }
}

class Triangle2 extends Shape2 {
 
 int side1, side2;
 Triangle2(int s1, int s2) {
  
  side1 = s1;
  side2 = s2;
 }
 
 public void area() {
  
  System.out.println("Area of Triangle : "+(0.5 * side1 * side2));
 }
}

public class HierarchicalInh {

 public static void main(String[] args) {
  
  Rectangle2 r = new Rectangle2(23,19);
  Triangle2 t = new Triangle2(15,6);
  Shape2 s = r;
  s.area();
  s = t;
  s.area();
 }
}
OUTPUT
C:\>javac HierarchicalInh.java
C:\>java HierarchicalInh
Area of Rectangle : 437
Area of Triangle : 45.0

No comments:

Post a Comment