2

First I know this is quite dirty job, and if there is a way, it may be consider "bad practice". Unfortunately, I have to explore the possibility.

I would like to know if I can cast an object that in practice implements a Interface but in fact do not. I mean, the class implements all the methods but do not have the "implement interface" in the declaration. Additionally, I would prefer to do this and finally get the Object typed. Example below

interface IA{
void method();
}

class CB{

    void method(){;}

}

public class foo{
    public static void main(String[] args){
    /*magic to cast the object without exception*/
    IA ob= (IA) new CB(); 
    ob.method(); 
    }
}

I want to get this IA object at the end.

ender.an27
  • 703
  • 1
  • 13
  • 35
  • not clear with the question. – Abie Nov 18 '15 at 12:22
  • Java won't let you do this- Java is a strongly typed language – ControlAltDel Nov 18 '15 at 12:22
  • See this http://stackoverflow.com/questions/840322/how-does-the-java-cast-operator-work – Slimu Nov 18 '15 at 12:23
  • 3
    sounds like you want to use an [Adapter Pattern](https://en.wikipedia.org/wiki/Adapter_pattern) and the approach I would take is to create a new class that implements the interface and contains an instance of the object. the new class will redirect calls to the appropriate methods in the contained object which has the methods but does not implement the interface. – Richard Chambers Nov 18 '15 at 12:26
  • Java let you compile that, but will not run: //ClassCastException – Java bee Dec 05 '20 at 21:16

4 Answers4

6

Consider a much safer alternative.

Wrap the object you want to cast, into a class that implements the interface and delegate the method calls to the wrapped object.

Example:

public class CBWrapper implements IA {
    CB target;

    public CBWrapper(CB target) {
        this.target = target;
    }


    @Override
    void method() {
        target.method();
    }
}
kupsef
  • 3,357
  • 1
  • 21
  • 31
3

You cannot cast an Object to interface it doesn't implements.

You can access object's method using reflection and call a specific method by name or whatever.

However, I think you should ask yourself what you want to do and is there a simpler way to do it.

BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
  • I have consider this other. Including reflection. I do it due to licensing restrictions. I know this is bad, and dangerous. – ender.an27 Nov 18 '15 at 12:34
0

How the implements keyword is used to get the IS-A relationship?

The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes.

hurricane
  • 6,521
  • 2
  • 34
  • 44
0

You can’t create an object from an interface because in Java interfaces don't have a constructor.

A better way would be to play with softer alternatives.

bfontaine
  • 18,169
  • 13
  • 73
  • 107
Anurag
  • 1,162
  • 6
  • 20