• Post Reply Bookmark Topic Watch Topic
  • New Topic

why i need interface and abstract class ?  RSS feed

 
Alvin chew
Ranch Hand
Posts: 834
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, why we need interface ? it only contains the method definition with no method body , then why a class want to implement it ?, since i have to re-write my method definition with method body in my new class again.
and also to abstract class , even it allow us to extends defined methods , i can just simply put all the method into my new class .
what are the advantages as we do that ? because the code readability ? please enlight me ....
tq
 
Sebastiaan Kortleven
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll start with the interfaces.
Interfaces are used to hide the implementation of a class. For eg if I write a class that sends out an email if you give it a certain text and ppl want to use that class, they only need to know which methods there are, not how they are implemented. So they use the interface, if (in a next version) the class changes from plain text email to html emails, I can keep the interface the same, make some extra private methods and the user doesn't have to change anything to his program...
For abstract classes:
Eg take a motorised vehicle abstract class. Some items are in common for all motorised vehicles, they all have an engine and a nr of cilinders, but there doesn't exists a 'Motorised Vehicle', there only exists things like: Car, Motorbike,...
So they all share some methods, but you shouldn't be able the instanciate a 'Motorised Vehicle'..
Hope I could clear some things up for you...
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to read How my dog learned polymorphism.
 
Alvin chew
Ranch Hand
Posts: 834
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so, interface is not for reuse ?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!