简体   繁体   English

简单例子的多态性

[英]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()); 的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. 我会有相同的输出,但在什么情况下,或者当我们应该调用Cow类的方法,以及什么时候形成Whale类。 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. 在上面的例子中,我创建了由Cow和Whale扩展的Animal类。 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(); 在你的例子中,为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. 当使用Cow cow = new Whale() ,对象被创建为Whale但只能访问Cow方法。

For example, if you add to your Whale class the method: 例如,如果您向Whale类添加方法:

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没有名为getDeepestDive()的方法:

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

In your example you assigned an instance of Whale to a Cow . 在您的示例中,您为Cow分配了一个Whale实例。 However the object is still a Whale . 然而,对象仍然是Whale That is why you get the same output. 这就是为什么你得到相同的输出。 Now consider this Whale class: 现在考虑这个Whale课程:

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 . 然而,这个新的Whale实现有一个新的方法,没有在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 . 在第二个示例中,您将在方法调用上获得编译错误,因为此方法未在类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. 如果这是真的,我们应该在NG频道上看到它。 A more proper example may be: 一个更恰当的例子可能是:

Animal -> Cow, Dog, Cat, Whale 动物 - >牛,狗,猫,鲸鱼

Person -> Student, Driver, Developer etc. 人 - >学生,司机,开发人员等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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