Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference between abstract class and an interface

 
rafa
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between abstract class and an interface
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rafa, please note that JavaRanch has a naming standard. http://www.javaranch.com/name.jsp
Please update your display name.
As to your question, it has been asked quite a few times. Why not try a search in this forum?
 
Jamal Hasanov
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JLS 9.1.1.1 abstract Interfaces
-------------------------------
Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.
Difference:
Abstract class is a simple class which may have undefined(with declaration only) methods. You can extend only one abstract class.
Interface is not a class-It's a special "type" in Java. You can extend(implement) more than one interface.
That's the difference. You can read RHE or Khalid Mughal's book for additional info.
Jamal.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As was mentioned, you can do a seach in this forum and find a lot of information on this.
In short, however, an abstract class, unlike an interface, can contain non-abstract methods. In fact, an abstract class need not have any abstract methods. This means that classes that extend an abstract class can inherit fully functional methods, rather than reimplementing them at every level. This can be very useful for classes that share identical functionality. Also, abstract classes can contain instance variables, whereas interfaces only contain final static members. Take the following example:

Had this been implemented with an interface, both of the subclasses would have had to define identical code for the setName and getName methods. Also, the name variable itself would have been a static member, which is probably not what you would have wanted as all Americans would have the same name and all Germans would have the same name.
Unfortunately, Java does not allow multiple inheritance. Therefore, you can only extend one class, but you can implement multiple interfaces.
I hope that helps,
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic