What is the output of this PHP code?
<?php abstract class Animal { abstract public function sound(); public function describe() { return "This animal says: " . $this->sound(); } } class Dog extends Animal { public function sound() { return "Woof"; } } $dog = new Dog(); echo $dog->describe(); ?>
Look at how the describe method uses the abstract sound method implemented in the subclass.
The abstract class Animal defines an abstract method sound and a concrete method describe that calls sound. The subclass Dog implements sound returning "Woof". So calling describe on a Dog instance returns "This animal says: Woof".
What happens when you run this PHP code?
<?php abstract class Vehicle { abstract public function move(); } $car = new Vehicle(); ?>
Remember, abstract classes cannot be directly created as objects.
Abstract classes cannot be instantiated directly. Trying to create an object of an abstract class causes a fatal error.
What error will this PHP code produce?
<?php abstract class Shape { abstract public function area(); } class Circle extends Shape { public function area($radius) { return 3.14 * $radius * $radius; } } $circle = new Circle(); echo $circle->area(5); ?>
Check if the method signatures match exactly between abstract and subclass methods.
The abstract method area in Shape has no parameters. The subclass Circle defines area with a parameter $radius. PHP requires the subclass method to have the same signature, so this causes a fatal error.
Choose the correct PHP code that defines an abstract class with one abstract method run.
Remember abstract methods cannot have a body and must be inside an abstract class.
Option A correctly defines an abstract class Runner with an abstract method run without a body. Option A is invalid because abstract methods must be inside abstract classes. Options C and D incorrectly provide a method body for the abstract method, which is not allowed.
Given this PHP code, how many methods must the class Smartphone implement to avoid errors?
<?php abstract class Device { abstract public function powerOn(); abstract public function powerOff(); public function reset() { $this->powerOff(); $this->powerOn(); } } abstract class Phone extends Device { abstract public function call($number); } class Smartphone extends Phone { public function powerOn() { echo "Powering on"; } public function powerOff() { echo "Powering off"; } // Missing call method implementation } ?>
Count all abstract methods from parent classes that are not yet implemented.
The abstract class Device has two abstract methods: powerOn and powerOff, both implemented in Smartphone. The abstract class Phone adds one abstract method: call, which Smartphone has not implemented yet. So Smartphone must implement exactly one more method: call.