PhysicsTeacher.in

High School Physics + more

Java program – class hierarchy using base class and child class

Here is a Java program that helps you to understand the concepts of class hierarchy in Java (parent-child class hierarchy in java). This program implements the concepts of the base class and child class in Java. Use of the keyword “extends” to inherit a parent (or base class) by the child class is demonstrated in this program. “super” keyword is also used here.

Java program implementing class hierarchy (using base class and child class)

class Base
{
int l,b,h;
Base(int l, int b, int h)

{
this.l=l;
this.b=b;
this.h=h;
}

double getMult()
{
System.out.println(“Inside Base getMult”);
return l*b*h;
}

void showMessage()
{
System.out.println(“showMessage method in Base class” );

}

void sop(String s)
{
System.out.println(s);
}

void showMessage(String s)//method overloading
{
sop(s);
sop(“I am written by sop”);
}
}

class Child extends Base
{
int r;

Child(int l,int b,int h,int r)
{
super(l,b,h);//call to super must be first statement in constructor
this.r=r;

}

double getMult()//method overriding

{ System.out.println(“Inside Child getMult”);

return r*r;

}

void showMessage()

{

super.showMessage();

System.out.println(“From Child showMessage..”);

}

}
class HierarchyTest
{
public static void main(String args[])
{
double result;
Base b1 = new Base (10,20,30);
result=b1.getMult();

System.out.println(“output = “+result);
Child c1=new Child(1,2,3,4);
result=c1.getMult();
System.out.println(“output = “+result);

System.out.println(“Child class values here::L= “+c1.l + ” B= “+c1.b+ ” H= “+c1.h);
c1.showMessage();
b1.showMessage(“calling showmessage on b1”);
c1.showMessage(“calling showmessage on c1”);
}
}

See also  Java Program - how to use static variable and static method?
Scroll to top
error: physicsTeacher.in