Object-Oriented Programming Wrap-up
This section covered the core principles of Object-Oriented Programming (OOP) in Java. You learned about:
- Inheritance: How to create new classes that inherit properties and methods from existing classes.
- Interfaces: How to define contracts that classes can implement.
- Abstract Classes: How to create classes that cannot be instantiated and must be subclassed.
- Packages: How to organize your classes into packages.
Exercise
Write a Java program that models a simple zoo.
Requirements:
- Create an
Animalinterface with aspeak()method. - Create an abstract class
Mammalthat implements theAnimalinterface. TheMammalclass should have anameproperty. - Create two concrete classes,
DogandCat, that extend theMammalclass. Implement thespeak()method in each class to print "Woof!" for the dog and "Meow!" for the cat. - Create a
Zooclass that has a list ofAnimals. Add a method to theZooclass to add new animals to the list. - Create a
Mainclass with amainmethod to test your classes. In themainmethod, create aZooinstance, add aDogand aCatto it, and then iterate through the animals in the zoo and call theirspeak()method.