简体   繁体   English

使用父级配置或“将父级降级到子级”实例化子对象

[英]Instantiate Child Object with Parent config or 'downcast parent to child'

I am not sure what the best practice for downcasting from parent to child or creating a B ( extends A ) out of A is. 我不知道从父向下转换到儿童或创建一个最好的做法Bextends A )出来的A是。

As an example I have two classes: 例如,我有两个类:

The parent one: 父母一:

public class SoccerPlayer  {

    private String name;
    private SoccerShoe shoe;
    private SoccerJersey jersey;
    /* ... */
}

And the child one: 和孩子一个:

public class Goalkeeper extends SoccerPlayer {

    private GoalkeeperGlove glove;
    /* ... */
}

Now a regular soccer player wants to be a Goalkeeper. 现在,一名普通的足球运动员希望成为一名守门员。 What can I do? 我能做什么? Obviously the following would not work: 显然,以下操作无效:

    SoccerPlayerArrayOfTeamA[0] = new SoccerPlayer("Robert");

    /*... new career path ...*/

    SoccerPlayerArray[0] = (Goalkeeper) SoccerPlayerArray[0]

But that is what I would say "I want to do"... 但这就是我要说的“我想做的事” ...
The new Instance of the child class ( Goalkeeper ) should have all variable configurations as the old Instance of the parent class ( SoccerPlayer ). 子类的新实例( Goalkeeper )应该具有与父类的旧实例( SoccerPlayer )一样的所有变量配置。 (eg name , jersey ...) Is there an OOP way to do that I do I have to set every variable manually as in the following? (例如namejersey ...)是否有一种OOP方法可以执行,我必须手动设置每个变量,如下所示?

    /*... new career path ...*/

   SoccerPlayer temp = SoccerPlayerArray[0]
   SoccerPlayerArray[0] = new Goalkeeper(temp.getName());
   SoccerPlayerArray[0].setJersey(temp.getJersey());

Checkout Decorator Design Pattern. 结帐装饰设计模式。 Eg Java IO classes. 例如Java IO类。

When any object dynamically wants to change its behavior then you can wrap that object with the desired object. 当任何对象动态地想要改变其行为时,您可以使用所需的对象包装该对象。 Like if C wants to become B then B should have a constructor which accepts C and then the methods in B should use C where ever appropriate. 就像如果C wants to become B那么B应该有一个接受C的构造函数,然后B中的方法应在适当的地方使用C。 Best example is when FileInputStream wants to become BufferedInputStream you can just create BufferedInputStream by passing FileInputStream in its constructor but it does not need to copy properties of FileInputStream . 最好的例子是,当FileInputStream wants to become BufferedInputStream您可以通过在其构造函数中传递FileInputStream来创建BufferedInputStream ,但是它不需要复制FileInputStream属性。

向守门员添加一个复制构造函数,该复制构造函数接受SoccerPlayer作为参数。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM