Code Lab

Shapes and method overriding

HardClasses15 min

Write a class Shape and two subclasses of it: Rectangle and Circle.

  • new Shape(name) saves name (a string) in the field name.
  • The method area() of Shape returns 0.
  • describe() of Shape returns the text <name>: area <area>, for example 'Rectangle: area 6'. It takes the area from this.area() and rounds it to 2 digits after the point with Math.round(area * 100) / 100. The number is printed the default JavaScript way: 6, 3.14, 2.5.
  • new Rectangle(width, height) creates a shape with the name 'Rectangle'. Its area() returns width * height.
  • new Circle(radius) creates a shape with the name 'Circle'. Its area() returns Math.PI * radius * radius, not rounded.
  • Rectangle and Circle use method overriding: each one has its own area() method in the class body (not a property set in the constructor).
  • Do not write describe() in Rectangle and Circle. They get it from Shape, and for every instance it must show the area of that shape.
  • Sizes are numbers, 0 or more.

Examples

new Rectangle(2, 3).describe()

Returns 'Rectangle: area 6'

new Circle(1).describe()

Returns 'Circle: area 3.14'

new Shape('Point').area()

Returns 0

Asked at EPAM · Source

Loading the editor...
  1. Rectangle 2 x 3: area 6 and its describe()
  2. Circle with radius 1: area PI, describe() rounds to 3.14
  3. A plain Shape has area 0 and uses its own name

Hidden tests run on Submit.