将子类对象分配给超类实例类型只是为了覆盖概念?或者我们也在为别的东西这样做? [英] Assigning subclass object to Superclass instance type is only for overriding concept?or we are doing this for something else also?

查看:35
本文介绍了将子类对象分配给超类实例类型只是为了覆盖概念?或者我们也在为别的东西这样做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您是否将子类对象分配给超类实例类型仅用于覆盖?或者我们这样做也是为了其他目的?

Do you assign a subclass object to a Superclass instance type only for overriding? Or are we doing this for something else also?

示例:Sub 是 Super 的子类型,并且Super s = new Sub();

Example: Sub is subtype of Super and Super s = new Sub();

请解释.

推荐答案

当有人写这样的代码时,他/她试图遵循基本的 OO 设计原则,即 -

When someone writes code like this, he/she is trying to follow a basic OO design principle which says -

针对接口编程,而不是针对具体实现

Program to an interface, not to a concrete implementation

我在 one 中解释了这个原则我的博文.查看 Class Inheritance VS Interface Inheritance 部分.

I have explained this principle in one of my blog posts. Look in the Class Inheritance VS Interface Inheritance section.

总结这篇文章,当你使用父类型的引用来引用子类型的实例时,你会获得很大的灵活性.例如,如果您将来需要更改您的子类型实现,您将能够轻松地做到这一点,而无需更改您的大部分代码.

To summarize the post, when you use a reference of a parent type to refer to an instance of a sub-type, you get a lot of flexibility. For example, if you ever need to change your sub-type implementation in the future, you will be able to do that easily, without changing much of your code.

考虑以下方法 -

public void DoSomeStuff(Super s) {
    s.someMethod();
}

并调用此方法 -

DoSomeStuff(new Sub());

现在,如果您需要更改 someMethod 内部的逻辑,您可以通过声明一个新的 Super 子类型来轻松实现,例如 NewSubType,并更改该实现中的逻辑.通过这种方式,您将永远不必接触使用该方法的其他现有代码.您仍然可以通过以下方式使用 DoSomeStuff 方法 -

now, if you ever need to change the logic inside someMethod, you can easily do it by declaring a new subtype of Super, say NewSubType, and changing the logic inside that implementation. In this way, you will never have to touch other existing code which utilizes that method. You will still be able to use your DoSomeStuff method in the following way -

DoSomeStuff(new NewSubType());

如果您将 DoSomeStuff 的参数声明为 Sub,那么您也必须更改其实现 -

Had you declared the parameter of DoSomeStuff to be of Sub, you would then have to change its implementation too -

DoSomeStuff(NewSubType s) {
    s.someMethod();
}

它也可能链接/冒泡到其他几个地方.

and it may also chain/bubble to several other places.

这篇关于将子类对象分配给超类实例类型只是为了覆盖概念?或者我们也在为别的东西这样做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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