D.2.2 Define the term inheritance.
a mechanism wherein a new class is derived from an existing class and reuse the fields and methods of that existing class without having to write (and debug!) them yourself
a process where one class acquires the properties (methods and fields) of another and which information is made manageable in hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
In Java, classes may inherit or acquire the properties and methods of other classes. A class derived from another class is called a subclass, whereas the class from which a subclass is derived is called a superclass.
extends is the keyword used to inherit the properties of a class.
/**
*
* @author andersonm
*/
public class Rectangle {
private int length;
private int width;
public Rectangle(int length, int width) {
this.length = length;
this.width = width; }
public void setLength(int length) {
this.length = length; }
public void setWidth(int width) {
this.width = width; }
public int getLength() {
return length; }
public int getWidth() {
return width; }
public int getArea() {
int a = getLength() * getWidth();
return a; }
@Override
public String toString() {
return "Rectangle{" + "length=" + length + ", width=" + width + '}';
}
}
/**
*
* @author andersonm
*/
public class Box extends Rectangle {
private int height;
public Box(int height, int length, int width) {
super(length, width);
this.height = height; }
public void setHeight(int height) {
this.height = height; }
public int getHeight() {
return height; }
public int getVolume() {
int v = super.getArea() * getHeight(); return v; }
@Override
public String toString() {
return "Box{" + "height=" + height + '}'; }
}
What is the output after the following code segment is executed?
/**
*
* @author andersonm
*/
public class TestBox {
public static void main(String[] args) {
Box r = new Box(3, 4, 5);
Rectangle rec = new Rectangle(3, 5);
Rectangle x = new Box(3, 4, 5);
System.out.println(r.getVolume());
System.out.println(r.getArea());
System.out.println(r.toString());
System.out.println(rec.toString());
System.out.println(rec.getArea());
System.out.println(x.getArea());
}
}