User Story
As an animal lover, I want to be able to simulate the sounds of different animals, so that I can learn more about the sounds they make and have fun exploring their characteristics.
This code provides a simple example of how to use virtual and override keywords in Apex to simulate the sounds of different animals. The code defines a base class called Animal
with a makeSound
method that prints a generic animal sound. It also creates two subclasses of Animal
called Dog
and Cat
, each of which overrides the makeSound
method with its own implementation of the sound the animal makes.
Using this code, the user can create instances of Animal
, Dog
, and Cat
classes, and call the makeSound
method on them to print out the corresponding sound that each animal makes. By exploring the different sounds that animals make, the user can learn more about their characteristics and behaviors, and have fun simulating and experiencing their sounds.
Code
public virtual class Animal {
public void makeSound() {
System.debug('Generic animal sound');
}
}
public class Dog extends Animal {
public override void makeSound() {
System.debug('Bark');
}
}
public class Cat extends Animal {
public override void makeSound() {
System.debug('Meow');
}
}
Animal myAnimal = new Animal();
myAnimal.makeSound(); // Output: "Generic animal sound"
Animal myDog = new Dog();
myDog.makeSound(); // Output: "Bark"
Animal myCat = new Cat();
myCat.makeSound(); // Output: "Meow"
EXPLANATION
In this example, we have a base class called Animal
with a makeSound
method that prints a generic animal sound. The Animal
class is marked as virtual
, which means that its methods can be overridden by subclasses.
We then create two subclasses of Animal
called Dog
and Cat
. Each subclass overrides the makeSound
method with its own implementation of the sound the animal makes.
Finally, we create instances of each class and call the makeSound
method on them. When we call makeSound
on the Animal
instance, it prints the generic animal sound. But when we call makeSound
on the Dog
instance, it prints "Bark", and when we call it on the Cat
instance, it prints "Meow". This is because the Dog
and Cat
classes have overridden the makeSound
method from the Animal
class.
Video
Video does not exists.