Saturday, April 8, 2017

Multilevel Inheritance

Multilevel inheritance is similar to our family relationship Grandfather-Father-Son. Son inherits characteristics from Father and Father inherits behaviors from Grandfather. Also Son inherits some behaviors from Grandfather as well. It is similar to Java Multilevel inheritance.

Examples: Alien IS-A Superhuman and Superhuman IS-A Human.


In this example we have three classes Human, Superhuman and Alien. Human can do basic things like eating, running and jumping. Superhuman inherits human abilities. They can do what human do as well as emitting laser beam and fly. Alien is even unbelievable. They can do what human and superhuman do. They also can invisible.

Human attribute: haircolor
Superhuman attribute: specialty

class Human
{
  String haircolor;

  public Human (String h) { haircolor = h;}
 
  public void eat()  { System.out.println("I can eat !!");}
  public void run()  { System.out.println("I can run !!");}
  public void jump() { System.out.println("I can jump !!");}
  public String getHairColor() { return haircolor; }
}

class Superhuman extends Human
{
  String specialty;
 
  public Superhuman (String hc, String specialty)
  {
super(hc);
this.specialty = specialty;
  }
 
  public void laserbeam()  {System.out.println("I can emit laserbeam !!"); }
  public void fly() { System.out.println("I can fly !!"); }
  public String getSpecialty() { return specialty; }
}

class Alien extends Superhuman
{
  public Alien (String hc, String s)
  {
super (hc,s);
  }
 
  public void invisible() {System.out.println("I can be invisible suddenly !!");}
}

public class MultilevelTest
{
  public static void main (String args[])
  {
     Superhuman s1 = new Superhuman("black","laser");
     System.out.println("Superhuman s1 created.");
     Alien a1 = new Alien("green","mind control");
     System.out.println("Alien a1 created.\n");

    System.out.println("Alien a1 can do following....");
    a1.eat();
    a1.run();
    a1.jump();
    a1.laserbeam();
    a1.fly();
    a1.invisible();

    System.out.println("\nSuperhuman s1 can do following....");
    s1.fly();
    s1.laserbeam();
    s1.eat();
    s1.jump();
    s1.run();
    System.out.println("s1: "+"hair color: "+s1.getHairColor()+" / specialty: "+s1.getSpecialty());
    System.out.println("a1: "+"hair color: "+a1.getHairColor()+" / specialty: "+a1.getSpecialty());
  }
}

Result:
Superhuman s1 created.
Alien a1 created.

Alien a1 can do following....
I can eat !!
I can run !!
I can jump !!
I can emit laserbeam !!
I can fly !!
I can be invisible suddenly !!

Superhuman s1 can do following....
I can fly !!
I can emit laserbeam !!
I can eat !!
I can jump !!
I can run !!
s1: hair color: black / specialty: laser
a1: hair color: green / specialty: mind control

No comments:

Post a Comment

Abstraction vs Interface

Abstract Interface method abstract and concrete abstract only, support default and static method ...