Objective: Exercise inheritance in Java. Java program: 1. Create a class named R
ID: 3773915 • Letter: O
Question
Objective:
Exercise inheritance in Java.
Java program:
1. Create a class named Rectangle that has instance variables height and width. Provide a constructor that initializes the instance variables based on parameter values, getter and setter methods for the instance variables, a toString method, and a method named computeSurfaceArea(), that returns the surface area of
the rectangle.
2. Create a child class named RectPrism that contains an additional instance variable named depth. Provide a constructor, getter and setter methods for the new instance variable, and a method named computeVolume(), that returns the volume of the rectangular prism. Override the toString() and the computeSurfaceArea() methods.
3. Write an application called Demo, that instantiates a rectangle and a rectangular prism, and tests all the methods.
Explanation / Answer
Rectangle.java
public class Rectangle {
double width;
double height;
public Rectangle(double width, double height) {
super();
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public String toString() {
return "Rectangle [width=" + width + ", height=" + height + "]";
}
public double computeSurfaceArea(){
return this.width*this.height;
}
}
RectPrism.java
public class RectPrism extends Rectangle{
double depth;
public RectPrism(double width, double height, double depth) {
super(width, height);
this.depth = depth;
}
public double getDepth() {
return depth;
}
public void setDepth(double depth) {
this.depth = depth;
}
public double computeVolume(){
return this.width*this.height*this.depth;
}
@Override
public String toString() {
return "RectPrism [depth=" + depth + ", width=" + width + ", height=" + height + "]";
}
public double computeSurfaceArea(){
return 2*(this.width*this.height+this.height*this.depth+this.depth*this.width);
}
}
Demo.java:
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Rectangle rectangle=new Rectangle(12, 15);
System.out.println("Rectangle");
System.out.println("Width:"+rectangle.getWidth());
System.out.println("Height:"+rectangle.getHeight());
System.out.println("Surface Area:"+rectangle.computeSurfaceArea());
System.out.println();
RectPrism prism=new RectPrism(12, 36, 14);
System.out.println("RectPrism:");
System.out.println("Width:"+prism.getWidth());
System.out.println("Height:"+prism.getHeight());
System.out.println("Depth:"+prism.getDepth());
System.out.println("Volume:"+prism.computeVolume());
System.out.println("Surface Area:"+prism.computeSurfaceArea());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.