Monday, August 29, 2011

Hierarchical Inheritance Example


/*Class A is a parent class of both class B and class C i.e one Parent class has many sub classes.
And this is the concept of Hierarchical Inheritance.*/
//A.java
public class A
{
void DisplayA()
{
System.out.println("I am in A");
}
}

//B.java
public class B extends A
{
void DisplayB()
{
System.out.println("I am in B");
}
}

/c.java
public class C extends A
{
void DisplayC()
{
System.out.println("I am in C");
}
}

//MainClass.java
public class MainClass
{
public static void main(String args[])
{
System.out.println("Calling for subclass C");
C c = new C();
c.DisplayA();
c.DisplayC();

System.out.println("Calling for subclass B");
B b = new B();
b.DisplayA();
b.DisplayB();
}
}

Output =>
Calling for subclass C
I am in A
I am in C
Calling for subclass B
I am in A
I am in B

11 comments:

  1. Itz really helpful... thnx a lot...

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. save the above prg. in the name of A.java - and compile it - it give 3 errors - how to rectify?-A.S.Ravi - 9842196141

    ReplyDelete
  4. how to run the above prg.? - a.s.ravi - 09842196141

    ReplyDelete
  5. Save program as MainClass.java not A.java

    ReplyDelete
  6. it has many classes so i have doubt that which name should i take to save this programme to execute

    ReplyDelete
  7. Hi Noor,

    Please follow the follwoing steps,
    1. First create package.
    2. Then create the 'A.java' parent class under the above package.
    3. Then create 2 child classes 'B.java' and 'C.java' extends parent class 'A.java' under same package.
    4. Finally create main class 'MainClass.java'
    5. All code mentioned in my blog. Just follow the steps and copy past and finally run the 'Main.java' class and it will execute the output.

    Regards,
    Arun

    ReplyDelete