Pet Program with Polymorphism
Description
This program incorporates the OOP Inheritance concept to design classes to represent Pet, Cat, and Dog objects.The client program incorporates the OOP Polymorphism concept to process a variety of subclass objects.
Each object, either cat or dog, has the name, breed, weight, and age as data members.
A dog object has an additional data member called "group".
A cat object has an additional data member called "body type".
Both dog and cat objects have a talk() method.
Cat: Meow, meow, meow
Dog: Woof, woof, woof
Dog: Woof, woof, woof
The superclass Pet defines the common features that apply to any types of pets.
Data members: name, breed, weight, and age
constructors
getters and setters
talk method
toString method
constructors
getters and setters
talk method
toString method
The subclasses Cat and Dog inherits the superclass Pet's features and adds additional features.
Cat: body type
Dog: group
Dog: group
Both Cat and Dog classes override the superclass' talk method. Basically, the Pet's talk method does not know what message should be returned by the subclasses. So the subclasses determine how to implement this method.
Associated Concepts:
OOP - Inheritance
OOP - Polymorphism
OOP - Polymorphism
Algorithm:
Class diagrams:
Client program:
Client program:
The client program creates an ArrayList of superclass Pet
and adds subclass objects such as dogs and cats to the
ArrayList in random order.
It then invokes the talk() method in the loop using the superclass references.
As we know, the actual subclass object's talk() method is executed.
It then invokes the talk() method in the loop using the superclass references.
As we know, the actual subclass object's talk() method is executed.
Source Code
Superclass Pet classSubclass Cat class
subclass Dog class
Client program