Inheritance in Java
To create a child class in Java we must first start with a parent class (or superclass), like this one...
public class Rectangle {
private int length;
private int width;
// Constructor that accepts length and width
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
// Default constructor
public Rectangle() {
this(3, 5); // Calls the constructor with length 3 and width 5
}
// Getter for length
public int getLength() {
return length;
}
// Getter for width
public int getWidth() {
return width;
}
// Getter for area
public int getArea() {
return length * width;
}
// Setter for length
public void setLength(int length) {
this.length = length;
}
// Setter for width
public void setWidth(int width) {
this.width = width;
}
} // Rectangle
public class Box extends Rectangle {
private int height;
// Constructor
public Box(int length, int width, int height) {
super(length, width); //calls parent class constructor
this.height = height;
}
// Default constructor
public Box() {
super();
this.height = 5;
}
// Getters & Setters
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getVolume() {
return super.getArea() * height;
}
}//Box
public class MainClass {
public static void main(String[] args) {
Box myBox = new Box();
System.out.println(myBox.getLength());
System.out.println(myBox.getWidth());
System.out.println(myBox.getHeight());
System.out.println(myBox.getVolume());
} //main
} //MainClass3 5 5 75
public class MainClass {
public static void main(String[] args) {
Box myBox = new Box();
System.out.println(myBox.getLength());
System.out.println(myBox.getWidth());
System.out.println(myBox.getHeight());
System.out.println(myBox.getVolume());
System.out.println(myBox.getArea());
} //main
} //MainClass
public class Box extends Rectangle {
private int height;
// Constructor
public Box(int length, int width, int height) {
super(length, width);
this.height = height;
}
// Default constructor
public Box() {
super();
this.height = 5;
}
// Getters & Setters
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getVolume() {
return super.getArea() * height; // Calls Rectangle's protected getArea()
}
@Override
public int getArea() {
throw new UnsupportedOperationException("getArea() is not supported for Box objects.");
}
}//Box

Comments
Post a Comment