Zach Cochran
by Zach Cochran
2 min read

Categories

Tags

This has been a subject that’s been on my bucket list to learn for a while now. Spent some time this evening going back over some more basic level java tutorial videos and the subject of polymorphism came up. I always thought that it sounded pretty daunting (aside from the thought be being turned into a cute little sheep), but it turns out that it’s pretty simple conceptually.

Once again, the examples from this are coming straight from Mr. Derek Banas’s tutorial video. I know that this is a big oversimplification, but I feel that it does a really good job of having it make sense.

To me, I think the easier way of approaching it is to call it method override instead. Basically when you have a subclass that inherits from the parent, it’s possible for you to override the method in the parent with a method of the same name in the child.

Let’s say that we have a top level class of Animal. In this class, we implement a single method of makesSound. This by default is just going to return back a string of “Moooo”:

public String makesSound() {
   return "Moooo";
}

We’re then going to go ahead and create 3 sub classes off of Animal: Cat, Dog, and Cow. In all of these cases, the new classes are going to extend the base Animal class, so that they can inherit the makesSound method.

And that’s great and all, except for the fact that Cats and Dogs don’t make a “Mooo” sound (at least not usually, I’m not one to judge).

Our Cow class ends up being super basic:

public class Cow extends Animal {
}

Inside of Dog and Cat we’ll be rewriting the makesSound method so that it returns back the correct sound:

Cat.java

public class Cat extends Animal {

   public String makesSound() {
       return "Meow";
   }
}

Dog.java

public class Dog extends Animal {

   public String makesSound() {
       return "Woof";
   }
}

In both of these cases, objects of either type that call the makesSound method are going to use their respective method.

If we go back to the Animal class now and update to add in a main function to actually do something, we can create instances of everything and see what we get back:

public class Animal {

   public String makesSound() {
       return "Moooo";
   }

   public static void main(String[] args) {

       Animal bob = new Animal();
       Cat billy = new Cat();
       Dog john = new Dog();
       Cow joe = new Cow();

       System.out.println(bob.makesSound());
       System.out.println(billy.makesSound());
       System.out.println(john.makesSound());
       System.out.println(joe.makesSound());
   }
}

This will give us the following output

Moooo
Meow
Woof
Moooo

EZPZ

Here’s another pretty good video on the subject:

💚