dcsimg
Sorry to bother you all. Still I dont understand how interface works exactly. please help me.
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Abdul_Ambalam
Posted On:   Friday, November 28, 2003 12:43 PM

Hi,
I went thro' all of the interfaces related Q&A but Still I have doubt abt interface. for example : Runnable interface has run method without implementation. How come our class become Thread when we implement this interface. And any class can be cloneable by implementing Cloneable interface which has nothing in itself. how? Sorry to bother you guys.

Re: Sorry to bother you all. Still I dont understand how interface works exactly. please help me.

Posted By:   Nick_Maiorano  
Posted On:   Saturday, November 29, 2003 09:19 AM

Abdul,



In java, interfaces are used only to declare methods, not implement them. So you never have real code in interfaces other than method signatures. Classes, on the other hand, can implement these interfaces. So in the case of the Runnable interface, it only declares the run() method with no implementation. It is your duty to write a class that implements the interface by providing some real code in the run() method. The way it becomes a real thread is by giving our class to the Thread class. Suppose I create a class (MyOwnRunnableClass) that implements the Runnable interface, I can then create a thread out of it like this:



Thread myThread = new Thread(new myOwnRunnableClass());

myThread.start();



This magic really happens in the thread class which creates a thread and calls the run method we implemented in myOwnRunnableClass. This occurs when we call the start() method.



Cloneable, on the other hand, is what we call a tag interface. These are special interfaces in java that have no methods and serve only to categorize classes. For example, the cloneable tag interface tells the Object class that it can do a field-for-field copy of any class that implments the cloneable interface. It does this like this:



protected Object clone(Object objectToClone) throws CloneNotSupportedException{

if (objectToClone instanceof Cloneable)

// ok to do field-for-field copy

else

throw new CloneNotSupportedException()};

About | Sitemap | Contact