简单例子的多态性

时间:2015-10-10 08:20:55

标签: java oop polymorphism

我想我已经开始理解这个话题了,但并不是完全理解。有人可以通过这个例子向我解释:

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";
        }
    }
}

这个叫什么区别:

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

和此:

Whale whale = new Whale();

的System.out.println(whale.getName());

我将具有相同的输出,但在什么情况下或者当我们应该为Cow类调用方法时,以及何时形成Whale类。 对不起,如果我给出了太愚蠢或太简单的例子。我希望你没有理解我想说的话。 提前致谢。

4 个答案:

答案 0 :(得分:3)

理解多态性是一个很好的问题。我不确定鲸鱼应该延伸牛;),但我可以向你展示一些不同的结构:

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";
        }
    }
}

在上面的例子中,我创建了由Cow和Whale扩展的Animal类。我可以创建我的动物列表并显示它们的名字。 在你的例子中,为Cow cow = new Whale()制作一个对象没有区别;和鲸鱼鲸鱼=新鲸鱼(); 你觉得好吗?

答案 1 :(得分:1)

使用Cow cow = new Whale()时,对象的创建方式与Whale类似,但只能访问Cow个方法。

例如,如果您向Whale类添加方法:

public int getDeepestDive() {
  // some code
}

此代码可以使用:

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

此代码会告诉您Cow没有名为getDeepestDive()的方法:

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

答案 2 :(得分:1)

在您的示例中,您为Whale分配了Cow的实例。但是对象仍然是Whale。这就是为什么你得到相同的输出。现在考虑这个Whale类:

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

重写方法将始终在实例化的对象类型上调用方法,除非显式强制执行(使用强制转换)。但是,这个新的Whale实现有一个新方法,该方法未在Cow上定义。因此,您可以致电:

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

但你不能写:

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

在第二个示例中,您将在方法调用上收到编译错误,因为此方法未在类Cow上定义。

答案 3 :(得分:1)

或者当您创建一个处理奶牛的方法时,差异将变得更容易理解,比如说收集所有奶牛,鲸鱼,狗,马等的名称。

此方法不需要了解鲸鱼或任何其他牛的子类。不过它应该有效。示例:

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

而且我不确定为什么鲸会延长牛。如果这是真的,我们应该在NG频道上看到它。一个更恰当的例子可能是:

动物 - &gt;牛,狗,猫,鲸鱼

人 - &gt;学生,司机,开发人员 等

相关问题