简体   繁体   中英

Class with two constructors taking different objects as parents

I want to create a new class, which has to be able to take two different types of objects (with nearly the same functions and variables). I am trying to use two constructors for this. Since both possible argument classes have nearly the same variables in them, I want to refer to them with the same variable named parent .

What I tried:

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 
}

This is not possible because parent is a duplicate, what would be a way to solve this?

Edit

The only thing Segment and Base have in common are some variables telling the start end end points, to connect new Segments to. Other than that the Base is standing still, and the Segment's are moving

The OO way to do this is to create a common super class for both classes:

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 { ... }

Then your class looks like this:

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

That is, you only have one constructor and one field referring to the super class.

Let base and segment implement the same interface. Now change the parent's type to that interface (and remove the other parent field)

You have some ways to do:

  1. Declare parent is Object: Object parent; then cast it if needed. It's very simple but isn't good.

  2. Use inheritance by define the base class / interface like 2 answers below. I prefer interface if they have same properties and methods. Otherwise, use class.

  3. Use generic like Segment or Segment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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