Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interface(runnble)

 
nethanjana indrakeela
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

the runnable interface has only run methode signature,

we can use that after imlement,but why we use it like that?

why can't we use full run methode in our own class?
what is the deferent that ether interface and full methode in class?

Indarakeela
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You certainly can write your own class with a "public void run()" method in it. This class would not implement the "Runnable" interface. However, what you cannot do is then use this class to create a Thread. Even though the class has the "run" method defined, when you create a Thread with a Runnable, it is expecting something of type "Runnable," as this is the only way to gaurentee that the "run" method exists in the class.

For example, suppose you mistyped "run" as "ryn". Without implementing Runnable, the compiler would compile happily. However, with Runnable, you would get an error message stating something to the effect of "Your class is incomplete -- you need to implement the "run" method." You look back, thinking But I did implement the run method and discover that it is misspelled. You correct the misspelling and everything compiles happily.

(No, this is not far-fetched. Someone here recently had this problem, albeit with the actionPerformed method in another interface -- which was spelled actionperformed -- without the capital 'P.')
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Joel said, there is nothing stopping you from creating a run() method without implementing Runnable. In fact, there is nothing special in and of itself about the run() method defined in Runnable. What makes it special is that the Thread class expects to find this method in order to call it. You can create a Thread object that uses another class that implements Runnable and the expected run() method. For more details about how this works, you should google or use the Saloon's search tool for something about threading in Java.

HTH

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic