COMP2247 - Algorithms and Data Structures

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

OOP - Polymorphism Pet Program Payroll Program Class Roster Program



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



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

The subclasses Cat and Dog inherits the superclass Pet's features and adds additional features.

Cat: body type

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

Algorithm:

Class diagrams:



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.

Source Code

Superclass Pet class



Subclass Cat class



subclass Dog class



Client program



Sample Run



Video