简体   繁体   中英

Polymorphism on simple example

I think I'm starting to understand this topic, but not completely. Can somebody 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 is the difference when is called this:

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.

It's good question to understand Polymorphism. I am not sure that Whale should extends Cow ;), but I can show you a bit of different structure:

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

        ArrayList<Animal> myAnimals = new ArrayList<Animal>();
        myAnimals.add(animal1);
        myAnimals.add(animal2);
        //show all my animals
        for (Animal animal : arrayList) {
            System.out.println(animal.getName());

        }


    }


    public static class Animal {
        public String getName() {
            return "Im general animal";
        }
    }

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

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

In above example I created Animal class which is extended by Cow and Whale. I can create list of my animals and display they names. In your example is no difference to make a object for Cow cow = new Whale(); and Whale whale = new Whale(); Is it clear for you?

When using Cow cow = new Whale() , the object is created like a Whale but only has access to Cow methods.

For example, if you add to your Whale class the method:

public int getDeepestDive() {
  // some code
}

This code will work:

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

This code will tell you that Cow doesn't have a method called getDeepestDive() :

Cow whale = new Whale();
System.out.println(whale.getDeepestDive());

In your example you assigned an instance of Whale to a Cow . However the object is still a Whale . That is why you get the same output. Now consider this Whale class:

public static class Whale extends Cow {
  public String getName() {
    return "Im whale";
  }
  public void submerge() {
    System.out.println("Hunting submarines");
  }
}

Overriding a method will always call the method on the type of object that is instantiated unless forced explicitly to do otherwise (with a cast). However this new Whale implementation has a new method which is not defined on Cow . Therefore you can call:

Whale whale = new Whale();
whale.submerge();

But you cannot write:

Cow mascaradedWhale = new Whale();
mascaradedWhale.submerge();

In the second example you will get a compile error on the method call, as this method is not defined on the class Cow .

Or maybe the difference will become more understandable when you create a method that processes cows, let's say one that collects the names of all cows, whales, dogs, horses, etc.

This method does not need to know about whales or any other subclass of cow. Nevertheless it should work. Example:

public static List<String> collectNames(List<Cow> cows)
{
        return cows.stream().map(c -> c.getName()).collect(Collectors.toList());
}

And I'm not sure why whale extends cow. If this is true we should see it on NG channel. A more proper example may be:

Animal -> Cow, Dog, Cat, Whale

Person -> Student, Driver, Developer etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM