Object Oriented Programming (OOP) – Polymorphism

Placeholder Image

 

Polymorphism means an object takes on many forms. Any object that can pass more than one IS-A test is considered to be polymorphic.

 

Let’s look at this java gist and make sense of it.

First we have:

public abstract class Animal
{
public abstract void eat();
}

An abstract class serves the purpose of containing an abstract method.

@Override

Next, we have  Fish and Dog classes that inherit from the Animal class. We also have Goldfish inherit from the Fish class. Each class has a specific sys Out, but what’s important is that we have a strange new syntax, @Override. The eat() method is being overwritten:

class Fish extends Animal
{
@Override
public void eat()
{
System.out.println(“I eat like a fish!”);
}
}

What’s cool about overriding methods is we can use a specific method that has it’s own properties like eat() and treat it as a generic function. In java code lingo we’re essentially saying, “Hey, you know how we made that method in the Animal class? Well, all the animals should all know what eat means.” If I want to call all or some of them to eat it makes no sense to write the same code over and over. It may not seem like a big deal for our example but imagine if we had thousands of species of animals in our program and how time consuming it would be to manually call the eat() method on all of them.

Lastly, we created a LinkedList  and iterate through the list to call the eat() method on each of them:

public class Program
{
public static void main(String[] args) {
List animals = new LinkedList();

animals.add(new Fish());
animals.add(new Goldfish());
animals.add(new Dog());

for (Animal currentAnimal : animals)
{
currentAnimal.eat();
}
}
}

The IS-A test is being satisfied by inheritance… Goldfish IS-A Fish and Fish IS-A Animal.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: