w3resource

Scala Program: Shape class with nested dimensions

Scala OOP Exercise-15 with Solution

Write a Scala program that creates a class Shape with a nested class Dimensions to store the dimensions of a shape.

Sample Solution:

Scala Code:

class Shape {
  private var dimensions: Dimensions = _

  def setDimensions(width: Double, height: Double): Unit = {
    dimensions = new Dimensions(width, height)
  }

  def getDimensions: Dimensions = dimensions

  class Dimensions(val width: Double, val height: Double)
}

object ShapeApp {
  def main(args: Array[String]): Unit = {
    val shape = new Shape()
    shape.setDimensions(12.0, 18.0)

    val dimensions = shape.getDimensions
    println(s"Width: ${dimensions.width}")
    println(s"Height: ${dimensions.height}")
  }
}

Sample Output:

Width: 12.0
Height: 18.0

Explanation:

In the above exercise -

  • The Shape class is defined with a nested class Dimensions that represents shape dimensions. In the Shape class, dimensions are stored in a private property of type Dimensions.
  • The setDimensions method sets the shape's width and height by creating the Dimensions object and assigning it to the dimensions property.
  • The getDimensions method returns the Dimensions object representing the shape's dimensions.
  • The ShapeApp object contains the main method where we can test functionality. It creates an instance of the Shape class, sets the dimensions using the setDimensions method, and retrieves them using the getDimensions method.
  • Finally, the program prints the shape width and height using string interpolation.

Scala Code Editor :

Previous: Class ContactInfo and customer with composition.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.