-1

I was wondering if it was possible for me to implement an interface after the object has been created?

I have'nt found anything on it except for this link but it's not really what i'm looking for plus it's for android programming

Is there any way to acheive this or do i have to extends the object then add the interface to it?

No code as it is a theorical question.

Community
  • 1
  • 1
Chax
  • 1,041
  • 2
  • 14
  • 36
  • I don't understand your question. – Sotirios Delimanolis Mar 17 '15 at 19:45
  • See http://stackoverflow.com/questions/5196941/can-you-force-a-java-object-into-implementing-an-interface-at-runtime – Chin Mar 17 '15 at 19:51
  • 1
    Does this help? https://blogs.oracle.com/poonam/entry/how_to_implement_an_interface – unigeek Mar 17 '15 at 19:52
  • @unigeek it does, your answer and levious's answer helped me understand. I see that i have to get a reference thus implementing an interface would be as creating a new object type. Thanks! – Chax Mar 17 '15 at 20:02
  • You cannot cast an object to an interface when it was not included in the class declaration. But you can use a dynamic proxy to implement any interface. – eckes Mar 17 '15 at 20:34

1 Answers1

2

You can't implement an interface after an object has been created. Implementing an interface is not a method you can call on an object.

Even if you could, what would be the point? By implementing an interface, you "make a promise" that you will define the methods that are in the interface. In fact your program won't even compile if you don't. So if you want to implement an interface, you need to do it in the class definition and you have to define all the methods of the interface. Only then can you create instances of the class. You can't change the methods of an object, or add to it.

levious
  • 76
  • 2
  • 5
  • Great answer, I did'nt thought of the function definition. The only way to do this would be to reference an object class and then implement the said interface to it. Thus it's rather useless, as it would be as the same of just defining the said function in the said class... thanks – Chax Mar 17 '15 at 20:05