0

我有这种情况

class Parent {
    int data;
    public Parent(int data) {
        this.data = data;
    }
}

class Child extends Parent {
    int childData;
    public Child(int data, int childData) {
        super(data);
        this.childData = childData;
    }
}

我手头有一个Parent. 我想向childData它添加功能。我最近一直在用 Javascript 编程,这很简单,我在精神上移植了设计模式,却没有意识到这在 Java 中是不平凡的。

假设我可以完全控制Child类代码,这样做的最佳做法是什么?我可以在不克隆的情况下做到这一点吗?是否需要修改Parent类才能使其正常工作?

当然在最坏的情况下(这听起来很糟糕)有这个解决方案:

new Child(parent.data, childData);

由于Parent的数据都是公开的。

具体问题(我倾向于忘记包含在 Java 问题中)是我有一个Config.testUser返回用户的方法,我想向它添加一个数据以使其成为InitialScanUser,这是一个添加UserinitialScanAlgorithm类型数据的a InitialScanAlgorithmConfig.testUser生活在一个不能依赖的包中InitialScanAlgorithm

4

2 回答 2

0

Make Parent instances immutable and you can just delegate to an instance of Parent.

See Effective Java, Item 16: Favor composition over inheritance.

于 2013-06-10T22:48:44.497 回答
0

It is not trivial. An instance class cannot be changed (although it can be referenced as a superclass reference, but the instance itself cannot change).

A more elegant way would be (if you use the construct a lot) to add a constructor that accepts a parent instance.

public Child(Parent parent, int childData) {
  ....
}
于 2013-06-10T22:48:46.810 回答