简体   繁体   中英

ClassCastException when trying to convert Interfaces

I'm looking for help in understanding why am getting ClassCastException while trying to cast ParentInterface to ChildInterface.

Sample code

{ParentInterface P1}

{SampleClass P2 implements P1}

{ChildInterface C1 extends P1}

SampleClass sampleClass = new SampleClass();
ChildInterface childI = (ChildInterface) sampleClass;

To be specific what am doing [Implementation of above Logic]:

getInterface(){
return (ChildInterface)ParentInterfaceHelper.INSTANCE;
}

private static class ParentInterfaceHelper {
    private static final ParentInterface INSTANCE;
    static{
     INSTANCE = new SampleClass();
    }

}

am getting run time failures with exceptions

Exception in thread "main" java.lang.ClassCastException:

My understanding:

This Exception is due to as I am creating a object which is Implemented by ParentClass, so the reference is for ParentInterface rather then ChildInterface & thus the code execution fails at run time. Am I right?

From your description, I think you missed the fact that a class can implement multiple interfaces.

In your example, SampleClass only implements ParentInterface, not ChildInterface. You could let SampleClass implement ChildInterface, and it will implicitly also implement ParentInterface. You can also add different interfaces.

class SampleClass implements ChildInterface1, ChildInterface2

public class ParentInterfaceHelper {
    private static final SampleClass INSTANCE;
    static{
     INSTANCE = new SampleClass();
    }

    public static ParentInterface getParentInterface(){
      return INSTANCE;
    }

    public static ChildInterface1 getInterface1(){
      return INSTANCE;
    }

    public static ChildInterface2 getInterface2(){
      return INSTANCE;
    }
}

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