Java LAB 8
Java LAB 8
LAB # 8
INHERITANCE
OBJECTIVE:
To study inheritance and using super to call superclass constructors.
THEORY:
In summary, when you derive a new class from a base class, the process is
additive in terms of what makes up a class definition. The additional members
that you define in the new class establish what makes a derived class object
different from a base class object. Any members that you define in the new
class are in addition to those that are already members of the base class.
The inclusion of members of a base class in a derived class so that they are
accessible in that derived class is called class inheritance. An inherited
member of a base class is one that is accessible within the derived class. If a
base class member is not accessible in a derived class, then it is not an
inherited member of the derived class, but base class members that are not
inherited still form part of a derived class object.
Inheritance Basics:
To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword. To see how, let’s begin with a short
example. The following program creates a superclass called A and a subclass
called B. Notice how the keyword extends is used to create a subclass of A.
class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Output:
super(parameter-list);
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
double volume() {
return width * height * depth;
}
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
}
}
Output:
LAB TASK