Answer the following questions based on the following Rectangle class: public cl
ID: 3604337 • Letter: A
Question
Answer the following questions based on the following Rectangle class:
public class Rectangle
{
private int length;
private int width;
public Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}
public int area()
{
return length * width;
}
)
a) Write a class Cube:
-It should inherit from Rectangle
-It should have one instance variable for height
-It should have one constructor that takes 3 parameters (length, width, and height)
-You should NOT include any other methods or instance variables
b) Write the toString method for Rectangle – if length is 3 and width is 2, it should return “3 x 2”
c) Write a volume method for Cube that uses the area method in the Rectangle class
d) Explain why I made the instance variables (length and width) in Rectangle private instead of public
Explanation / Answer
Myclass.java
//reactangle class defination
class Rectangle
{
private int length;
private int width;
Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}
public String toString()
{
return length+" * "+ width;
}
public int area()
{
return length * width;
}
}
//cube class defination
class Cube extends Rectangle
{
//instance varible declaration
private int height;
//Cube class construtor with three parameters
Cube(int l,int w,int h)
{
super(l,w);
this.height=h;
}
//cube method defination
public int Volume()
{
return area() * height;
}
}
//Main function defination
public class MyClass {
public static void main(String args[]) {
//Object creation for Cube class
Cube c =new Cube(10,20,30);
//display cube volume
System.out.println("Volume of Cube is " + c.Volume());
//display rectangle area
System.out.println("Area of Rectangle : "+c.toString() +" " + c.area());
}
}
Output :
Volume of Cube is 6000
Area of Rectangle : 10 * 20 200
d) The private access modifier is accessible only within class.
Access Modifier within class within package outside package by subclass only outside package
Private Yes No No No