简体   繁体   English

为什么在面向对象的OO编程中实例化变量中的超类和子类?

[英]Why in OO programming for casting objects instantiate super class and subclass in a variable?

For eg: ParentObj A = new ChildObj(); ((ChildObj) A).childMethod(); 例如: ParentObj A = new ChildObj(); ((ChildObj) A).childMethod(); ParentObj A = new ChildObj(); ((ChildObj) A).childMethod();

I see lots of instances like this in object oriented programming, would it be easier to just declare the ChildObj as ChildObj A = new ChildObj() instead of using the parent object as the starter of the of the creation of the object? 我在面向对象的编程中看到了很多这样的实例,将ChildObj声明为ChildObj A = new ChildObj()而不是使用父对象作为创建对象的开始者会更容易吗?

What would be the use cases of this example to any object oriented programming? 对于任何面向对象的编程,该示例的用例是什么?

And will the A object be the ChildObj in this declaration or ParentObj? 并且A对象是该声明中的ChildObj还是ParentObj?

Is there like a performance boost and such as to doing it this way or its a use case base thing if there is any? 有没有像这样的性能提升和诸如此类的提高性能(如果有的话)?

thanks noob here. 谢谢新手在这里。

Its my personal opinion and mostly its true that there is no use case of such declaration, like 我个人的看法,并且基本上是这样的,即没有此类声明的用例,例如

ParentObj A = new ChildObj(); ParentObj A =新的ChildObj();

We use to hide the child object under Parent references in below cases 在以下情况下,我们用于在“父对象”引用下隐藏子对象

  • We don't know, how the object initialized 我们不知道对象如何初始化
  • We don't know the actual child class details 我们不知道实际的孩子班级详细信息
  • We have multiple child classes of same parent class and we just want to focus on overrided functions 我们有多个相同父类的子类,我们只想关注重写的函数
  • We are bound with a contract and just using function that fulfills the contract (Interface scenarios) 我们受合同约束,仅使用履行合同的功能(接口方案)

These are some of use cases. 这些是一些用例。

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

相关问题 为什么子类对象不能拥有超类构造函数 - why cant subclass objects hold super class constructor 将超级变量转换为类类型 - Casting the super variable to a class type 为什么我们不能使用父类的引用变量来访问其子类的方法(方法在父类中不可用)? - why cant we use a reference variable of super class to access methods of its subclass(methods not available in super class)? Java继承:如何在Super中声明静态变量并在子类中实例化它 - Java Inheritance: How to declare a static variable in Super and instantiate it in subclass 如何使JAXB实例化泛型超类的子类列表元素 - How to make JAXB instantiate subclass list element of generic super class 在子类之外访问 Java 超类变量? - Java super class variable accessed outside of subclass? 如何更改子类中超类的变量类型? - How to change the type of a variable of a super class in a subclass? 在超类方法中使用子类成员变量? - Use subclass member variable in super class methods? 为什么Java中的子类是超类的实例但不能分配给它? - Why is a subclass in Java an instance of the super class but not assignable to it? 在 Java 中,您可以将子类的对象存储为超类类型,为什么要这样做? - In java you're able to store objects of a subclass as a super-class type, why would you do this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM