w3resource

Scala Program: Abstract shape class with rectangle and circle subclasses

Scala OOP Exercise-4with Solution

Write a Scala program that creates an abstract class Shape with an abstract method area. Implement subclasses Rectangle and Circle that override the area method.

Sample Solution:

Scala Code:

abstract class Shape {
  def area: Double
}

class Rectangle(width: Double, height: Double) extends Shape {
  override def area: Double = width * height
}

class Circle(radius: Double) extends Shape {
  override def area: Double = math.Pi * radius * radius
}

object ShapeApp {
  def main(args: Array[String]): Unit = {
    val rectangle = new Rectangle(7, 5)
    println(s"Rectangle Area: ${rectangle.area}")

    val circle = new Circle(4.5)
    println(s"Circle Area: ${circle.area}")
  }
}

Sample Output:

Rectangle Area: 35.0
Circle Area: 63.61725123519331

Explanation:

In the above exercise,

  • The "Shape" class is an abstract class that defines the area method without implementation.
  • The "Rectangle" class extends the "Shape" class and provides an implementation of the area method based on the rectangle's width and height.
  • The "Circle" class also extends the "Shape" class and implements the area method based on the circle radius.
  • The "ShapeApp" object contains the main method where you can test functionality. It creates instances of Rectangle and Circle, and calls their area methods to calculate and print the respective areas.

Scala Code Editor :

Previous: Calculate the factorial with MathUtils Object.
Next: BankAccount class with deposit and withdrawal methods.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.