与两个构造师一起上课,以不同的对象为父母



我想创建一个新类,该类必须能够采用两种不同类型的对象(具有几乎相同的函数和变量(。我试图为此使用两个构造函数。由于两个可能的参数类中都有几乎相同的变量,因此我想用名为parent的相同变量引用它们。

我尝试的是:

class Segment{
  float phi;
  float theta;
  float len;
  Base parent;
  Segment parent;
  public Segment(Base parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;
    this.parent = parent;
  }
  public Segment(Segment parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;
    this.parent = parent;
  }
  // ... functions calling parent.variableName 
}

这是不可能的,因为父母是重复的,什么是解决这个问题的方法?

编辑

SegmentBase共同的唯一一件事是一些变量,告诉起点端点,将新段连接到。除此之外

这样做的方法是为这两个类创建一个普通的超级类:

public abstract class Super {
    // Here you declare all fields and methods that your classes have in common.
}
public final class Base extends Super { ... }
public final class Segment extends Super { ... }

然后您的班级看起来像这样:

public final class YourClass {
    ...
    private final Super parent; // only once
    public YourClass(Super parent, ...) {
        ...
        this.parent = parent;
    }
}

也就是说,您只有一个构造函数和一个字段,指的是超级类。

让base和segment实现相同的接口。现在,将父级的类型更改为该接口(并删除另一个父字段(

您有一些方法:

  1. 声明父级是对象:对象parent;然后在需要时施放。这很简单,但不好。

  2. 通过在下面的2个答案中定义基类/接口来使用继承。如果接口具有相同的属性和方法,我更喜欢它们。否则,使用类。

  3. 使用诸如段或段的通用

最新更新