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!...

34 comments:

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

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

    ReplyDelete

  3. 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
  4. 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
  5. Very Well! Great content, this is too helpful for us, Thanks for sharing this with us. Keep Sharing.
    java training in yamunanagar

    ReplyDelete
  6. Nice blog..well explained abstract class it was very useful.Thank you..Hadoop Training in Chennai

    ReplyDelete
  7. Excellent article!!! Good work, your concept is really helpful for me. Thanks for your contribution in sharing such wonderful information.
    Java Training Institute in Noida

    ReplyDelete

  8. Thanks For Sharing.It is very useful information

    orangetechnomind.com is one of the best institute to provide Software training courses in Velachery,OMR Chennai. We have best real time experts to provide Online classroom training institute in Chennai.
    Hadoop Training in Chennai
    Big Data Training in Chennai
    Selenium Training Chennai
    PHP Training in Chennai

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Nice site....Please refer this site also Our vision success!Training are focused on perfect improvement of technical skills for Freshers and working professional. Our Training classes are sure to help the trainee with COMPLETE PRACTICAL TRAINING and Real time methodologies
    Dot Net Training And Placement in Chennai | Best Dot Net Training in Chennai
    Software Testing Training Institute in Chennai | Best Software Testing Training Institute in Chennai
    core java and j2ee training | java institute in chennai
    PHP Course in chennaia | PHP Certification

    ReplyDelete
  11. Very useful Article
    Unic Sol is the best java training in Hyderabad with job placements. Along with java training full stack, mean stack, angular & testing tools training is provided by industry experts. We are the best java training in Hyderabad.

    ReplyDelete
  12. Nice article
    Unic Sol is the best best java training in Hyderabad with job placements. Along with java training full stack, mean stack, angular & testing tools training is provided by industry experts. We are the best java training in Hyderabad.

    ReplyDelete
  13. caddcentredelhigzb is Best Solidworks training centre in Ghaziabad. Solidworks is a software tool that is used right from the conceptualization of the design until the final manufacturing of the product.

    AutoCad training insti tute in Ghaziabad
    AutoCad training centre in Ghaziabad
    CADD centre in Ghaziabad
    Solidworks training centre in Ghaziabad
    Ansys training in GTB Nagar
    Staddpro training in GTB Nagar
    Revit coaching in GTB Nagar
    3ds Max coaching in GTB Nagar

    ReplyDelete
  14. Good Post! it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.

    Spring Boot and Micro services Training in Gurgaon
    Java Training in Gurgaon
    Java Framawork Training in Gurgaon

    ReplyDelete
  15. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.
    Data Analytics Training in Gurgaon

    ReplyDelete
  16. Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuff like this.

    DevOps Course in Pune

    ReplyDelete
  17. Thank so much for sharing knowledge, Digiperform-Gurgaon visit this links for graping more knowledge about digital marketing.

    ReplyDelete
  18. Nice Blog..It was so informative and usefull..Keep update. If you are looking for full stack development training in noida

    ReplyDelete
  19. Our trainer emphasizes hands-on learning practical skills that can be applied in real-world scenarios.
    Digital Marketing Training In Kukatpally

    ReplyDelete
  20. Buying YouTube subscribers instantly catapults your channel ahead, offering a swift enhancement in visibility and social proof. This strategic maneuver is essential for creators looking to solidify their presence in a crowded digital landscape. With a tailored selection of budget-friendly packages, this service is accessible to content creators across the spectrum, ensuring no channel is left behind. It paves the way for organic growth by establishing a foundation of credibility, which in turn attracts more viewers and potential collaborations. The simplicity and security of the process allow creators to focus on what they love most—creating engaging and innovative content. This investment not only boosts the quantitative metrics of your channel but also significantly improves the perception of your content's quality and reliability. Opting for this service is a decisive step towards achieving digital prominence and building a dedicated community around your unique offerings.
    https://www.buyyoutubesubscribers.in/

    ReplyDelete
  21. In the bustling metropolis of Delhi, Lasik surgeons stand as beacons of hope for those seeking liberation from visual constraints. With unparalleled expertise, these medical professionals wield the latest in laser technology to sculpt the cornea with utmost precision, addressing the broad spectrum of refractive errors. Their commitment to excellence is not just in the surgical act but in the compassionate care they provide, guiding patients with clarity and support through their vision correction journeys. Equipped with world-class facilities, these surgeons perform with a perfect blend of science and artistry, aiming for outcomes that not only meet but often exceed patient expectations. Their dedication has positioned Delhi as a premier destination for individuals from around the globe seeking the highest standard of Lasik surgery. Every procedure is a testament to their pursuit of perfection, ensuring that each patient steps into a world of visual clarity with confidence.
    https://www.visualaidscentre.com/

    ReplyDelete
  22. Buying YouTube views cheaply is a tempting option for content creators seeking a quick and cost-effective method to boost their video's visibility. This approach is especially appealing to those on a tight budget or just starting their YouTube channel, offering an immediate increase in view counts at a lower cost. While the initial outlay is minimized, it's crucial to ensure that the service provides views from real users to avoid violating YouTube's policies. Cheap views can serve as a springboard, enhancing the video’s appeal to potential viewers and the algorithm alike. However, creators should proceed with caution, considering the quality and source of these views to ensure they contribute positively to their channel’s long-term growth. This strategy, when used wisely, can be an entry point to gaining organic growth and higher engagement levels on the platform.
    https://www.buyyoutubeviewsindia.in/

    ReplyDelete
  23. Cheap website hosting in India is revolutionizing the way individuals and small businesses establish their online presence, offering an affordable yet robust platform to launch websites. These services provide an optimal blend of essential features such as free domain registration, ample storage, and significant bandwidth, catering to the diverse needs of the digital landscape without breaking the bank. High uptime rates ensure persistent online visibility, critical for maintaining user engagement and building a loyal customer base. Additionally, the inclusion of dedicated customer support teams guarantees swift resolution of technical issues, ensuring smooth and reliable website operations. This affordable hosting solution empowers budding entrepreneurs and small businesses in India to compete on a global scale, making the digital dream accessible to all.
    https://onohosting.com/

    ReplyDelete