Friday, January 31, 2014

Abstract Classes vs Interfaces in Java

Abstract Classes vs Interfaces in Java
Everybody knows that in abstract class we can define method body but not in interface, but there are more difference between abstract class and interface. For instance, now in Java 8 we can have default as well as static method in interface. In this post, we look in the difference between them as well as from Java 8 perspective and also the basic knowledge when to use abstract and interface.



   Abstract Classes Interfaces
Keyword(s) used Use the abstract and class keywords to define a class Use the interface keyword to define an
interface.
Keyword used by the
implementing class
Use the extends keyword to inherit from an abstract class Use the implements keyword to implement an
interface.
Default implementation An abstract class can provide default implementation of methods You cannot define methods in an interface; you
can only declare them.
Fields An abstract class can have static and non-static members You cannot have any instance variables
in an interface
Constants An abstract class can have both static (using static and final keyword) and non-static (using final keyword) constants declarations Interfaces can contain constant declarations If you
declare a field, it must be initialized. All fields are implicitly considered to be declared as public
static and final.
Constructors You can define a constructor in an abstract class (which is useful for initializing fields, for example). You cannot declare/define a constructor in an
interface.
Access specifiers You can have private and protected
members in an abstract class.
You cannot have any private or protected members
in an interface; all members are public by default.
Single vs. multiple
inheritance
A class can inherit only one class (which can be either an abstract or a concrete class). A class can implement any number of interfaces.
is-a relationship vs.
following a protocol
An abstract base class provides a protocol; in addition, it serves as a base class in an is-a relationship. An interface provides only a protocol.
It specifies functionality that must be
implemented by the classes implementing it
Default implementation
of a method
An abstract class can provide a default
implementation of a method. So, derived
class(es) can just use that definition and
need not define that method
An interface can only declare a method. All
classes implementing the interface must
define that method.
Difficulty in making changes It is possible to make changes to the implementation of an abstract class. For
example, you can add a method with default implementation and the existing derived classes will not break.
If there are already many classes implementing
an interface, you cannot easily change that
interface. For example, if you declare a new
method, all the classes implementing that
interface will stop compiling since they do not
define that method but it is possible with default method of Java 8

Java 8 update : Interface now contain default and static methods. 

Choosing Between an Abstract Class and an Interface

  • If you are identifying a base class that abstracts common functionality from a set of related classes, you should use an abstract class. If you are providing common method(s) or protocol(s) that can be implemented even by unrelated classes, this is best done with an interface.
  • If you want to capture the similarities among the classes (even unrelated) without forcing a class relationship, you should use interfaces. On the other hand, if there exists an is-a relationship between the classes and the new entity, you should declare the new entity as an abstract class.


Consider using abstract classes if any of these statements apply to your situation:
  • You want to share code among several closely related classes.
  • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

Consider using interfaces if any of these statements apply to your situation:
  • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
  • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
  • You want to take advantage of multiple inheritance of type.

JDK example:
An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines.

An example of a class in the JDK that implements several interfaces is HashMap, which implements the interfaces Serializable, Cloneable, and Map<K, V>. By reading this list of interfaces, you can infer that an instance of HashMap (regardless of the developer or company who implemented the class) can be cloned, is serializable (which means that it can be converted into a byte stream; see the section Serializable Objects), and has the functionality of a map. In addition, the Map<K, V> interface has been enhanced with many default methods such as merge and forEach that older classes that have implemented this interface do not have to define.

Example :
Let’s look at an example of choosing between abstract classes and interfaces in the Paint application. You can have Shape as an abstract base class for all shapes (like Circle, Square, etc.); this is an example of an is-a relationship. Also, common implementations, such as parent shape , can be placed in Shape. Hence, Shape as an abstract class is the best choice in this case.

In Paint, the user can perform various actions on shape objects. For example, a few shapes can be rotated, and a few can be rolled. A shape like Square can be rotated and a shape like Circle can be rolled. So, it does not make sense to have rotate() or roll() in the Shape abstract class. The implementation of rotate() or roll() differs with the specific shape, so default implementation could not be provided. In this case, it is best to use interfaces rather than an abstract class.




If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

15 comments:

  1. Abstraction in Java
    Real life Example of Abstraction

    Abstraction shows only important things to the user and hides the internal details. Real life example of abstraction is; we know how to ride the bike but we don't know internal function of bike.

    ReplyDelete
  2. Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
    java training in chennai |
    java training institutes in chennai

    ReplyDelete
  3. nice blog. thanks for sharing valuable information. It’s really good.Any one looking software courses nareshit is the best offline and online software training institute in Hyderabad and Chennai.

    ReplyDelete
  4. nice blog. thanks for sharing valuable information. It’s really good.Any one looking software courses nareshit is the best offline and online software training institute in Hyderabad and Chennai.

    ReplyDelete
  5. Nice blog..! I really loved reading through this article... Thanks for sharing such an amazing post with us and keep blogging...
    ios app development course

    ReplyDelete
  6. Thanks for sharing this valuable information to our vision.
    Java Online Training India

    ReplyDelete
  7. Thanks for sharing this valuable information to our vision.
    Java Online Training India

    ReplyDelete
  8. The Blog Content is very informative and helpful. Please share more content. Thanks.
    JAVA Training in Noida

    ReplyDelete
  9. Australia Best Tutor is one of the best Online Assignment Help providers at an affordable price. Here All Learners or Students are getting best quality assignment help with reference and styles formatting.

    Visit us for more Information

    Australia Best Tutor
    Sydney, NSW, Australia
    Call @ +61-730-407-305
    Live Chat @ https://www.australiabesttutor.com




    Our Services

    Online assignment help Australia
    my assignment help Australia
    assignment help
    help with assignment
    Online instant assignment help
    Online Assignment help Services

    ReplyDelete
  10. CIITN is the Best Php training institute in Noida and delhi Ncr. You will get Live Project Training on PHP by our PHP expert who have 5+ year industrial experience.Focus on practical and live project training. In our PHP training, we you will learn core PHP, advance PHP, HTML, CSS, JavaScript, jQuery, Bootstrap, Cake PHP and Wordpress.CIITN provides 100% job assistance in PHP training. CIITN is well known PHP coaching center because our 100% PHP students are placed now.


    Ciitnoida provides Core and java training institute in noida. We have a team of experienced Java professionals who help our students learn Java with the help of Live Base Projects. The object-oriented, class-based build of Java has made it one of most popular programming languages and the demand of professionals with certification in Advance Java training is at an all-time high not just in India but foreign countries too.

    By helping our students understand the fundamentals and Advance concepts of Java, we prepare them for a successful programming career. With over 13 years of sound experience, we have successfully trained hundreds of students in Noida and have been able to turn ourselves into an institute for best Java training in Noida.


    java training institute in noida
    php training in noida
    linux training in noida
    linux institute in noida
    java course in noida

    ReplyDelete

  11. Really very informative and creative contents. This concept is a good way to enhance the knowledge.
    thanks for sharing. please keep it up.
    Struts Training in Gurgaon

    ReplyDelete
  12. CIIT Noida provides Best MCA Courses in Noida based on the current

    IT industry standards that help students to get high paying jobs in Top MNCs. CIIT provides Best MCA Training in Noida, Greater Noida, and Ghaziabad.

    CIIT is one of the trusted MCA training institutes in Noida providing practical knowledge and 100% job assistance with basic as well as advanced

    level MCA subjects. CIITN is the best MCA college in Noida, greater noida, ghaziabad, delhi, gurgaon regoin.

    At CIIT MCA classes in Noida is conducted by subject experts corporate professionals with 9+ years of experience in managing real-time and live

    projects. Sofracle Nano Specialized MCA classes Noida is the perfect blend of academic learning and practical sessions to provide maximum exposure to

    students that transform an average student into a corporate professional whom companies prefer to hire.

    Best MCA College in Noida

    ReplyDelete
  13. Thanks for your valuable information about Java Programmig languages.Java is most important topic for Programmers. To kknow more about Java training institute checkout this link Java training in chennai | Java/J2EE training institute in chennai

    ReplyDelete