Inheritance Basics
Inheritance Basics
Inheritance-Basics
• Inheritance is one of the cornerstones of object-
oriented programming because it allows the
creation of hierarchical classifications.
• Using inheritance, you can create a general class
that defines traits common to a set of related
items.
• This class can then be inherited by other more
specific classes, each adding those things that
are unique to it.
• In the terminology of Java, a class that is inherited is
called a superclass.
• Superclass is also called as base class or parent
class.
• The class that does the inheriting is called a subclass.
• subclass is also called derived class or child class
or extended class.
Inheritance-Basics Cont…
Super Class Sub Class
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions
specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions
specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// Here, Box is extended to include weight.
class BoxWeight extends Box {
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m)
{
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15,
34.3);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " +
mybox1.weight);
}
}