Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Abstract Class & Interface

 
Luv Bhatia
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we should use Interface and When to use Abstract Class.
 
Bhaskar Chaganti
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both abstract classes and Interfaces have one goal in common. They should be used when the implementation is not specific. To make things clear let us say you have a 'Shape' class. Shapes could be of different kinds for e.g. a circle, a rectangle, a square etc. If 'Shape' class had a method called 'draw()', during designing you class, you cannot specifically say how this method should be defined. That's because each shape is drawn differently. So you have a draw method for square, a rectangle etc.
Here both abstract classes and interfaces can be used. Now if you want to enforce super-class sub-class relationship between shape and square and other classes you use abstract classes. Whereas in interfaces such relationship is not enforced.
Hope it's clear now..
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Java In General(beginner) forum..
 
Elouise Kivineva
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally an interface is implemented to gain methods while a class is extended to gain information (instance variables) and perhaps methods as well.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question has been asked here many times before. Using the search tool, I found the following threads on the subject:
http://www.coderanch.com/t/386670/java/java/Classes-Abstract-Interface
http://www.coderanch.com/t/386847/java/java/Abstract-Interface
http://www.coderanch.com/forums/
http://www.coderanch.com/t/387081/java/java/difference-interface-abstract
http://www.coderanch.com/t/387121/java/java/Abstract-vs-Interface
http://www.coderanch.com/t/387137/java/java/Extends-vs-Implement
http://www.coderanch.com/t/387287/java/java/abstract-class-interface
And those are only from the first dozen matches out of a hundred! I'm sure one of those will answer your questions. If you still don't understand, feel free to use the search tool yourself.
Of course, we are always here to clarify any confusions you may have, so feel free to come back with more questions.
Keep coding!
Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic