Polymorphism on simple example

i think i’m starting to understand this topic, but not completely. can smbd explain to me on this example.

public class Solution
{
    public static void main(String[] args)
    {
        Cow cow = new Whale();

        System.out.println(cow.getName());
    }

    public static class Cow
    {
        public String getName()
        {
            return "Im cow";
        }
    }

    public static class Whale extends Cow
    {
        public String getName() {
            return "Im whale";
        }
    }
}

what the difference when Ive wrote

Cow cow = new Whale();
System.out.println(cow.getName());

and this

Whale whale = new Whale();
System.out.println(whale.getName());

i will have the same output, but in what cases or maybe when we should call the methods for the Cow class, and when form Whale class.
sorry if I gave too stupid or too simple example. I hope you undeerstood what I wanted to say.
thanks in advance.


Source: oop

Leave a Reply