0

I thought I know the basic idea of upcast & downcast, but this problem I encountered make me think again.

Currently, it compiled and work flawlessly. But when I try to do the unit test (by using mockito), it keeps pointing that my way of casting has issues.

I've tested every single possible solution that I can make up with, but none of it satisfies this mockito platform.

To make it clear, I've make a simplified version for my Superclass and Subclass as below:

@Entity
public class Parent{
  private String A;
  private String B;

  protected Parent(){
  }
// below are necessary getter setter n mapped column
...
}
--------------------------------
@Entity
public class Child extends Parent{
  private String C;
  private String D;

  protected Child(){
     super();
  }
// below are necessary getter setter n mapped column
...
}
---------------------------------

So above are two class that I will be using for downcasting and the class which will do such action as below:

public class People{
   public void CheckRelation(){
      Parent parent = new Child();
      parent = parentRepo(...); // to get some data
      Child child = (Child) parent;
   }
}

From what I know, that's the proper method to do downcasting, but I've got an issue with Parent parent = new Child(); that give an error of The constructor Child() is not visible by mockito

Since I can't make any change toward class Parent, so I went to change class Child() constructor from protected to public (which I know not a wise move and shall not be done).

This later result in an error of :

java.lang.ClassCastException: Parent cannot be cast Child

Class Child was created to add additional functions for Parent as it can't be altered anymore. So Child was used as a medium to handle specifics amount of data and that's why it's necessary to downcast Parent to child.

Even though compile wise it worked fine, I believe this mockito error due to java runtime is it? Or is it due to something else?

Appreciate any wise answer from everyone and thank you

Airul Fmy
  • 3
  • 2
  • You set `parent` to a new `Child` then immediate overwrite it. If `parentRepo` returns a `Parent` there's no guarantee it can be cast to a `Child`. Not every problem is best solved (or solvable) by inheritance. – Dave Newton Mar 27 '20 at 15:10
  • I suspect the same thing too, but can't think of any other workaround. Fyi, ```parentRepo``` will return ```Parent``` – Airul Fmy Mar 27 '20 at 15:15

0 Answers0