Bird
0
0

Given the abstract class and two child classes below, what will be the output?

hard📝 Application Q15 of 15
PHP - Inheritance and Polymorphism
Given the abstract class and two child classes below, what will be the output?
abstract class Shape {
    abstract public function area();
}

class Square extends Shape {
    private $side;
    public function __construct($side) {
        $this->side = $side;
    }
    public function area() {
        return $this->side * $this->side;
    }
}

class Circle extends Shape {
    private $radius;
    public function __construct($radius) {
        $this->radius = $radius;
    }
    public function area() {
        return 3.14 * $this->radius * $this->radius;
    }
}

$shapes = [new Square(4), new Circle(3)];
foreach ($shapes as $shape) {
    echo $shape->area() . " ";
}
A62.82 61
B16 28.26
CError: Cannot instantiate abstract class Shape
D6 28.26
Step-by-Step Solution
Solution:
  1. Step 1: Calculate area for Square

    Square side is 4, so area = 4 * 4 = 16.
  2. Step 2: Calculate area for Circle

    Circle radius is 3, so area = 3.14 * 3 * 3 = 28.26.
  3. Step 3: Understand output formatting

    The code echoes each area followed by a space, so output is "16 28.26 " without newline.
  4. Final Answer:

    16 28.26 -> Option B
  5. Quick Check:

    Area calculations correct, output matches [OK]
Quick Trick: Calculate each area, watch for spaces and no newline [OK]
Common Mistakes:
  • Confusing output formatting with newline
  • Trying to instantiate abstract class Shape
  • Incorrect area formulas

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes