转换为父类型 - Java [英] Casting to parent type -- Java

查看:107
本文介绍了转换为父类型 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个验证:

将子对象转换为父类型是否有任何增益?

Is there any gain in casting a child object to a parent type?

假设我有两个班级
家长孩子儿童正在扩展家长

Suppose I have the two classes Parent and Child. Child is extending Parent.

代码
有什么区别

Is there any difference in the code

Parent p = new Child();

Parent p = (Parent) new Child();

p 在调用任何
方法或以任何方式访问其任何一个成员方面有任何不同的行为?

Would p behave any differently on invoking any of its methods or accessing any one of its members in any way?

从我的结尾来看,两者是同样和铸造在这里是多余的。

From my end, the two are the same and casting here is redundant.

// ================================= =

//==================================

编辑:
我一直在寻求控制,作为开发者,
在哪种方法上调用 - <方法<来自儿童以外的strong>儿童或父母

I've been looking to have control, as the developer, on which method to call-- the method of Child or Parent, from outside Child.

因此,编码器会调用
Parent 的方法而不管
是否覆盖了该方法子类。也就是说,
子类的重写方法将被旁路,
该方法的实现将在子项上调用
对象。

So, the coder will look to invoke the method of Parent regardless of whether that method is overridden in the subclass. That is, the overridden method of the subclass will be by-passed, and the Parent implementation of that method will be invoked on the Child object.

推荐答案

不管,无论您通过哪种方式调用该方法,该对象的行为都会相同。

No, the object would behave the same regardless of the type of reference through which you call the method.

这是设计的 - 它允许子类覆盖其超类的方法。

This is by design - it allows subclasses to override methods of their superclasses.

在您的示例中,分配前的upcast具有没有效果 - 它将作为赋值的一部分隐式发生。

In your example, the upcast before assignment has no effect - it will happen implicitly as part of the assignment.

Parent p = (Parent) new Child();

调用者无法强制对象忽略其方法覆盖。这是的事情。否则,孩子永远不会强制执行自己的内部不变量。

The caller can't force an object to ignore its method overrides. This is a good thing. Otherwise, a child could never enforce its own internal invariants.

如果要允许调用者选择是调用父方法还是子方法,然后您的API可以提供两个方法。父母和孩子都可以确定如何支持每个人。

If you want to allow the caller to choose whether to call the parent method or the child method, then your API can provide two methods. Both the parent and the child can determine how to support each.

这篇关于转换为父类型 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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