简体   繁体   中英

How to make this interface as this parameter's type not throw “incompatible types” when it's assigned to an object that implements the interface?

Without irrelevant pieces, I have:

public interface A {
// contents
}

public class B implements A {
// contents
}

I'd like to follow the dependency interjection pattern by instantiating the object of class B in my main method then passing it into class C's constructor, instead of instantiating it in C's constructor.

public class C {
  private final B object;
  private int D;
}

public C(A object) {
  B = object;
  D = object.method();
}

public static void main(String[] args){
    C finalobject = new C(new B);
}

Essentially, I want to do something similar to what this question is based on.

I get the error:

C.java:137: error: incompatible types: B cannot be converted to A
      C finalobject = new C(new B());

How do I pass B into C's constructor with the interface as the parameter?

I've tried casting it, and I can't instantiate it as the interface in the first place for obvious reasons. I can't pass it in as the object's class type not only because it doesn't fit the specifications I have for how this program has to behave, but I'd like to learn how to do what I've been trying to do.

The definition of class C should be:

public class C {
  private final A object;
  private int D;
}

If you really need a B in C class, you have to change the C constructor to:

public C(B object) {
  B = object;
  D = object.method();
}

You're forgetting that there could also be a D, E, F, and G classes that implement A interface. Meaning what you're doing is wrong conceptually. Of course you know what you're passing inside and you know it is an instance of class B, however Liskov's Substitution Principle would suggest that you either deal entirely with B or deal entirely with A depending on what fits the role better. You shouldn't ever need to cast to a derived class.

So that said, your solution is simply the following:

public class C {
  private final A object;
  private int D;
}

Any methods you need to call in B should be added accordingly to A, and if you don't think that A is suited to have certain methods, then you should ask yourself if you should be passing an A instance to C to begin with.

Hope that helps!

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