single
Challenge: Model a Simple Inheritance Hierarchy
Sveip for å vise menyen
Recap: Inheritance, Visibility, and Overriding
You have learned that inheritance allows you to create a new class based on an existing one, using the extends keyword. This lets you reuse code and build logical relationships between classes. Visibility keywords—public, private, and protected—control which properties and methods are accessible from outside or inside the class and its subclasses. Method overriding lets a subclass provide its own implementation of a method defined in its parent class.
You are now ready to apply these concepts by modeling a simple class hierarchy representing animals and their behaviors.
Sveip for å begynne å kode
Create a class hierarchy to model animals and their sounds.
- Define a base class
Animalwith a public methodspeak()that outputs a generic message.- The
speak()method should output a message like:"Some generic animal sound".
- The
- Define a subclass
Dogthat extendsAnimaland overridesspeak()to output a dog-specific sound.- The
speak()method should output:"Woof!".
- The
- Define a subclass
Catthat extendsAnimaland overridesspeak()to output a cat-specific sound.- The
speak()method should output:"Meow!"
- The
Løsning
Takk for tilbakemeldingene dine!
single
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår