In: Computer Science
Question 2: Design a class named Square that contains data fields side and surfaceArea, and a method called getSurfaceArea(). Create a child class named Cube. Cube contains a getCubeSurfaceArea() method that calculates the cube surface area. Write a program called DemoSquare that instantiates a Square object and a Cube object and displays the surface areas of the objects. Use the methods created to set the value of the side, and return the surface area. Hint: square area= side*side, Cube surface area= 6 × side2
Code:-
class Square{ //class Square (parent class)
int side, surfaceArea;
public int getSide(){ //getter method to get value of side
return side;
}
public void setSide(int side){ //setter method to set value to
side
this.side= side;
}
public int getSurfaceArea(){ //method to calculate
surfaceArea
surfaceArea = side * side;
return surfaceArea; //return area
}
}
class Cube extends Square{ //class Cube (child class) extending
square
int side,area;
public int getSide(){ //getter method to get value of side
return side;
}
public void setSide(int side){ //setter method to set value to
side
this.side =side;
}
public int getCubeSurfaceArea(){ //method to calculate
CubesurfaceArea
area = 6 * side * side;
return area; //return area
}
}
public class DemoSquare{
public static void main(String[] args) {
Square sq = new Square();
//instantiate object of Square class
sq.setSide(10); //calling setter
method
System.out.println("Square
SurfaceArea : " + sq.getSurfaceArea()); //calling area
function
Cube cu = new Cube(); //instantiate
object of Cuve class
cu.setSide(10); //calling setter
method
System.out.println("Cube Area : " +
cu.getCubeSurfaceArea()); //calling area function
}
}
Output:-