• Post Reply Bookmark Topic Watch Topic
  • New Topic

creating an Instance of a class that Implements Runnable  RSS feed

 
Nikolas Nikolaou
Ranch Hand
Posts: 101
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. I'm reading about threads In Head First Java and the way an Instance of a class that Implements Runnable Is created confuses me a little.

public class MyRunnable implements Runnable ......

Runnable ThreadJob = new MyRunnable();


I thought I had to use this syntax :

MyRunnable ThreadJob =new MyRunnable();


 
Knute Snortum
Sheriff
Posts: 4279
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an important point. you should declare your variables as interfaces when possible. For instance:



Why declare as List instead of ArrayList? Because at some point some someone might want to change the code to:



Because you've declared the variable by its implementation, you are guaranteed this will work without further code changes.
 
Nikolas Nikolaou
Ranch Hand
Posts: 101
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.

I get It ! ... kind of.
This should be common practice unless you need specific methods that are not related to the implemented method(s) of the Interface. Is that correct ? I assume you wouldn't have access to those.
 
Knute Snortum
Sheriff
Posts: 4279
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nikolas Nikolaou wrote:Thanks for the reply.

I get It ! ... kind of.


Yeah, I know how that feeling!

This should be common practice unless you need specific methods that are not related to the implemented method(s) of the Interface. Is that correct ? I assume you wouldn't have access to those.


The implementation is free to create new methods and if you needed those, yes, you would declare your variable to be the implementation type. But as much as possible, declare the interface. Yes, this should be common practice.
 
Nikolas Nikolaou
Ranch Hand
Posts: 101
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok.It's clear for now.

Thanks!
 
Giovanni Montano
Ranch Hand
Posts: 434
7
Android Open BSD Slackware
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:This is an important point. You should declare your variables as interfaces when possible. For instance:



Why declare as List instead of ArrayList? Because at some point some someone might want to change the code to:



Because you've declared the variable by its implementation, you are guaranteed this will work without further code changes.

Hey Knute +1 also here, cristally clear your example
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!