• Post Reply Bookmark Topic Watch Topic
  • New Topic

How interfaces are used for code reusability  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I am a newbie to java programming.
In an interview,i was asked about how the interfaces are used for code reusablity and we are also achieving multiple inheritence through interfaces.
we also do not write any code in interfaces methods..?


Warm Regards..
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you implement any interface for your class like
class x implements yourInterface
then you have to write every abstract method you have in that interface. So you can force to override all those methods by using interface.

We can achieve multiple inheritance means, we can implement as many interfaces as we want but in java, we can extend only 1 class.. So sometimes its advisable to use interface instead of abstract class dependng on your design.

Yes, we cant write any code in methods of interface. Just declaration. The concrete class that implements interface has to write all the methods.
Hope you find it useful.
 
Shashank Prashar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Shreyas..

I know that we can achieve multiple inheritence through interfaces by implementing various interfaces in our class.
But basically my question was..

Code reusablity means..we have defined our code some where and then we are using it..

but the point is that we are not writing any code in the methods of interfaces..so where
we are achieving code resuability in that...and also we have to provide the body of that methods also..
 
Ranch Hand
Posts: 208
9
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not the classes that implement the interface that are getting the code reusability. It's the classes that are using the interface.

For example, we have interface Shape, and implementations Triangle and Square.


So the implementation code is different, but because they both implement Shape I'm allowed to do this



instead of doing this



The point is that I don't have to know what kind of Shape I'm working with to use the Shape type in a general way; code reuse is all in the implementation.
 
Shashank Prashar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Tina..

for such a lovely example..

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!