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

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