0

I have 2 interfaces

public interface A {
 method1();
 method2();
}

public interface B extends A {
  method3();
  method4();
  :
}

I am in need of converting (upcasting) B to A in one of class. But so far I could not figure out how do I do that.

Assume "methodWhichReturnB" is method which returns B.

public class C {

  public void method10() {
     A a = methodWhichReturnB; // din't work
     A aa = (A) methodWhichReturnB // din't work          
  }
}

I am getting compilation error "Inconvertible types; cannot cast B to A".

Is there way I can upcast B to A ?

ykas11
  • 1
  • 2
    why would you want that? About all it would achieve is making sure certain functionalities are no longer available. – Stultuske Aug 10 '22 at 07:34
  • 4
    Since `B extends A` assigning an instance that implements `B` to a variable of type `A` should work. If it doesn't then something is off in your code, i.e. "cannot cast B to A" would indicate that `B` does _not_ have `A` in its hierarchy. Please provide a [mcve]. – Thomas Aug 10 '22 at 07:36
  • It works on my side. You're missing to share something I think. Maybe some name clashes? – Matteo NNZ Aug 10 '22 at 07:40
  • Thanks folks. @MatteoNNZ - there was one name clash which was causing this. Got it fixed. Thanks. – ykas11 Aug 10 '22 at 16:09

0 Answers0