0

2 classes with the same name.

public class Predictor()
{
    String name;
    PredictorA predictorA;
    PredictorB predictorB;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public PredictorA getPredictorA() {
        return predictorA;
    }
    public void setPredictorA (PredictorA predictorA) {
        this.predictorA = predictorA;
    }
    public PredictorB getPredictorB() {
        return predictorB;
    }
    public void setPredictorB(PredictorB predictorB) {
        this.predictorB = predictorB;
   }
}

PredictorA and PredictorB too.

package predictor.version1 classes Predictor, PredictorA, PredictorB.

package predictor.version2 classes Predictor, PredictorA, PredictorB

Other class called Result with several methods.

import XX
public class Result()
{
    public void prediction(Predictor predictor)
    {
    ...
    predictor.getPredictorA().getName();
    ...
    }
}

I want to be able to use Predictor of package predictor.version1 and Predictor of package predictor.version2 in the class Result and the method prediction withour 2 classes Result.

Jesper
  • 202,709
  • 46
  • 318
  • 350
Regular
  • 37
  • 7
  • What you want is basic polymorphism. Have both Predictor classes (and possibly both PredictorA and both PredictorB classes) inherit from a common interface or superclass. – VGR Jul 18 '16 at 19:52
  • I can't do that. I can't change the classes (there are not exactly the same and they are generated with JAXB, I need them and they are inside other classes like Predictor). – Regular Jul 18 '16 at 19:54

1 Answers1

2

Importing two classes with the same name and then trying to use them won't work, because the compiler can ofcourse not know which one of the two classes you mean. You'll have to use the fully-qualified name of at least one of the classes instead of importing it.

For example:

package whatever;

import predictor.version1.Predictor;

public class Result {
    // Uses the Predictor from package predictor.version1 which was imported
    public void prediction(Predictor p) {
        // ...
    }

    // Use fully-qualified class name to indicate that Predictor
    // from package predictor.version2 should be used
    public void prediction(predictor.version2.Predictor p) {
        // ...
    }
}
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • But then I have the same code twice, haven't I? – Regular Jul 18 '16 at 19:56
  • If the two classes don't have a common superclass, then there's no way to avoid this. There's no way to write one method that works on two unrelated classes (well, maybe with reflection, but that's going to be really ugly and cumbersome and not type-safe). – Jesper Jul 18 '16 at 19:58