将子类的对象分配给超类引用的目的? [英] Purpose of assigning objects of subclass to a superclass reference?

查看:59
本文介绍了将子类的对象分配给超类引用的目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想这个问题。人们为什么将子类的对象分配给超类引用,如下所示:

I have always this question burning in me. Why do people assign objects of subclass to a superclass reference as below:

好处原因到底是什么?

public static void main(String[] args)
{
    A obj1 = new C(); //Why do this ?
    C obj2 = new C(); //When we can simply do this ???
}

class A
{}

class B extends A
{}

class C extends B
{}

我理解所有的逻辑,其中狗是动物但动物不是动物本质上不是狗。
我也碰到了此链接:为什么将子类对象分配给超类引用?,它问了与我类似的问题(但被标记为重复项,但没有相关链接:>编程到接口是什么意思?

I understands all the logic where a Class Dog is an Animal but Animals are not essentially Dogs. I've also bumped into this link: Why assign a subclass object to a superclass reference? which asked similar question as me (but was marked as duplicate with a non-relevant link: What does it mean to "program to an interface"?)

在这里:为什么将子类对象分配给超类引用? 为此,给出了一些模糊的答案。不幸的是,在用不相关的链接将其标记为重复之前,无法给出更多详细的答案。

In here: Why assign a subclass object to a superclass reference? Some vague answers were given as reason for doing so. Unfortunately no more detailed answers could be given before it was marked duplicated with an irrelevant link.

希望有人可以调查这个问题并给出分配原因的详细答复

Hopefully someone could look into this question and give a detailed reply on the reason of assigning objects of subclass to a superclass reference.

推荐答案

经典示例。存储可以绘制自己并在需要时绘制它们的对象的列表。

Classic example. Store list of objects that can draw themselves and draw them when needed.

List<Drawable> toDraw = new ArrayList<Drawable>();
// Add objects to draw
toDraw.add(new Circle(0, 0, 10));
toDraw.add(new Rectangle(10, 10, 20, 20));

// draw them
for (Drawable drawable : toDraw) {
  // each object knows how to draw itself
  drawable.draw();
}

如果明天有人实现一个新的可绘制对象(例如三角形),则此代码仍将起作用。

If tomorrow someone implement a new drawable (say triangle) this code will still work.

此代码也是的示例Open-Close 原则,即代码是开放的以便扩展,而封闭的则是修改。您无需更改绘制所有对象的代码(修改),但仍可以添加新的绘制对象(扩展名)。

This code is also an example of Open-Close principle, that says that the code is Open for extension, but Closed for modification. You don't need to change code (modification) that draws all object, but you can still add new drawables (extension).

这篇关于将子类的对象分配给超类引用的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆