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

46 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
  24. Join our esteemed healthcare team in Singapore and seize the opportunity to advance your nursing career in one of the world's most innovative and respected medical environments. We are seeking skilled Indian nurses ready to bring their expertise to our dynamic and multicultural healthcare setting. Successful candidates will enjoy access to the latest in medical technology and practices, ensuring a steep learning curve and professional advancement. Benefit from a competitive salary, tailored to match the high standard of living in Singapore, alongside a comprehensive benefits package to support your well-being. This is your chance to work within a collaborative framework that emphasizes continuous learning and excellence in patient care. Immerse yourself in the rich culture and diversity of Singapore, all while making a significant impact in the lives of patients. Join us now and be part of a team that shapes the future of healthcare.
    https://dynamichealthstaff.com/nursing-jobs-in-singapore-for-indian-nurses

    ReplyDelete
  25. In the vibrant heart of Ahmedabad, Dr. Ishaan Gupta emerges as a distinguished Breast Cancer Specialist, renowned for blending cutting-edge treatment strategies with profound compassion. His expertise spans across the latest surgical procedures and innovative therapies such as hormone therapy and immunotherapy, ensuring his patients receive comprehensive, state-of-the-art care. Dr. Gupta's holistic approach extends beyond clinical treatment, focusing on the psychological and emotional well-being of each patient, supporting them through every step of their journey. A fervent advocate for patient education, he ensures that individuals are well-informed about their treatment options, empowering them to make decisions that align with their values and preferences. His collaborative work ethic involves leading a team of experts to formulate personalized, multidisciplinary treatment plans. Dr. Gupta's dedication to excellence, coupled with his empathetic nature, makes him a beacon of hope and a leader in breast cancer care in Ahmedabad.
    https://drvirajlavingia.com/

    ReplyDelete
  26. In the heart of Mumbai, there's a breast cancer surgeon renowned for blending surgical expertise with a deeply empathetic approach to care. This doctor is at the forefront of employing cutting-edge surgical methods, from minimally invasive techniques to breast conservation strategies, prioritizing the preservation of breast integrity. Integral to a collaborative team of medical experts, the surgeon tailors a holistic treatment strategy that respects the individuality of each patient. With state-of-the-art facilities, the practice guarantees precision in both diagnosis and treatment. Education is paramount; patients are thoroughly briefed about their options, promoting informed decisions. This commitment extends beyond physical treatment, acknowledging the emotional journey of recovery. This Mumbai surgeon stands as a pillar of support, guiding patients with kindness and skill through their breast cancer journey.
    https://drnitanair.com/

    ReplyDelete
  27. A Breast Cancer Doctor in Gurgaon is a beacon of hope in the daunting landscape of cancer care, embodying a unique combination of expertise, empathy, and pioneering medical practices. These professionals are distinguished by their deep understanding of breast cancer's complexities and their dedication to offering individualized treatments tailored to each patient's specific needs. Utilizing state-of-the-art diagnostic tools and innovative treatment methodologies, they aim not only to treat the disease but to enhance the overall well-being and quality of life of their patients. In Gurgaon, these doctors are at the forefront of medical research, constantly seeking out new ways to combat breast cancer more effectively. Their approach is comprehensive, incorporating the latest advances in surgery, chemotherapy, radiation therapy, and hormonal treatments, ensuring that patients have access to the broadest possible range of therapeutic options. They foster an environment of trust and compassion, prioritizing patient comfort and support throughout the treatment process. Through their relentless commitment and holistic care philosophy, Breast Cancer Doctors in Gurgaon stand as pillars of strength and innovation in the fight against breast cancer.
    https://www.breastoncosurgery.com/

    ReplyDelete
  28. A Breast Cancer Oncologist in Pune is a specialized physician focusing on the non-surgical management of breast cancer. These experts employ treatments such as chemotherapy, radiation therapy, hormonal therapy, and targeted therapy to treat cancer effectively. They work within a multidisciplinary team to create personalized treatment plans tailored to each patient's unique needs. Their practice emphasizes early detection, accurate diagnosis, and continuous support throughout the treatment journey. Patient education is a key aspect, ensuring individuals are well-informed about their condition and treatment options. By applying the latest medical advancements and adhering to international standards, these oncologists aim to deliver compassionate care and improve patient outcomes.
    https://www.drshonanagbreastcancer.in/

    ReplyDelete
  29. Minoxidil is widely recommended for treating hair thinning in females, particularly for those experiencing androgenetic alopecia. Offered in 2% and 5% strengths, this topical treatment is applied directly to the scalp to enhance blood flow to hair follicles. This increased circulation helps extend the hair growth phase and improves follicle health. Over time, users often notice a reduction in hair shedding and a boost in hair density. Patience is crucial, as it may take several months to see visible results. While generally safe, some users might experience mild side effects such as scalp irritation. Continuous application is essential to sustain the benefits of regrowth.
    https://generichealth.com.au/minoxidil-3/

    ReplyDelete
  30. Smile Pro eye surgery is a cutting-edge, minimally invasive procedure designed to correct refractive errors, such as myopia and astigmatism. Utilizing advanced laser technology, it reshapes the cornea through a small incision, promoting rapid recovery and reducing complications like dry eyes. Delhi's top eye care centers, equipped with state-of-the-art technology and expert ophthalmologists, ensure high safety and success rates. The entire surgery typically takes less than 30 minutes, with most patients experiencing immediate visual improvement. Personalized pre- and post-operative care guarantees a superior patient experience. Smile Pro stands out as an excellent option for those seeking effective and reliable vision correction.
    https://medium.com/@pojagupta

    ReplyDelete
  31. LASIK Eye Surgery, or Laser-Assisted In Situ Keratomileusis, is a cutting-edge procedure designed to correct various refractive vision errors such as nearsightedness, farsightedness, and astigmatism. By utilizing advanced laser technology, LASIK reshapes the cornea to enhance visual acuity significantly. The surgery is minimally invasive and typically performed on an outpatient basis, ensuring a quick recovery and minimal discomfort. Patients often notice a dramatic improvement in their vision shortly after the procedure. Delhi's LASIK clinics boast state-of-the-art technology and experienced ophthalmologists, providing personalized care and outstanding results. Patient safety and satisfaction are prioritized, making LASIK a top choice for vision correction.
    https://www.linkedin.com/today/author/romila-chaudhary-b2194626

    ReplyDelete
  32. Our mobile app development company in Delhi NCR specializes in creating bespoke iOS and Android applications. Leveraging advanced technologies and agile methodologies, we deliver robust, scalable solutions tailored to your business needs. Our expert team focuses on seamless, user-centric designs to enhance user experiences. Trusted by startups and established enterprises across diverse industries, we pride ourselves on innovation and quality. From concept to deployment, our end-to-end services bring your vision to life. Partner with us to drive business growth and elevate your digital presence. Let us transform your ideas into powerful mobile solutions with excellence and creativity.
    https://olycoder.com/

    ReplyDelete
  33. Peer-to-peer (P2P) lending platforms in India offer an innovative way for investors to earn higher returns by directly lending to borrowers. These platforms, regulated by the Reserve Bank of India (RBI), ensure security and transparency in transactions. Investors can choose borrowers based on their risk appetite and expected returns, enabling diversified investment portfolios. Borrowers benefit from quicker loan approvals and competitive interest rates compared to traditional banks. Prominent platforms like Faircent and Lendingkart have gained popularity for their efficient matchmaking and risk assessment algorithms. With minimal intermediation costs, both parties enjoy better financial outcomes. P2P lending is especially attractive to those seeking alternative investment avenues with potentially higher yields. Proper due diligence is crucial to navigating the associated risks effectively.
    https://www.perannum.money/

    ReplyDelete
  34. Man and A Van Edinburgh is a trusted provider of flexible moving solutions designed to meet the needs of both residential and commercial clients in the Edinburgh area. Their friendly and experienced team specializes in short-distance moves, focusing on the careful transportation of small to medium-sized loads. From furniture deliveries to student relocations and office clear-outs, they cater to a wide array of moving needs. With a fleet of well-maintained vehicles, they promise reliable service at competitive rates. Committed to customer satisfaction, they prioritize clear communication throughout the moving process. Additionally, they offer eco-friendly packing options, aligning with their goal of reducing waste. Choose Man and A Van Edinburgh for an efficient, stress-free moving experience that adapts to your unique requirements. Trust them to handle your move with professionalism and care.
    https://eh1-edinburghremovals.co.uk/man-and-van-edinburgh/

    ReplyDelete
  35. Nice post! definitively I will come back to update me on this technology Thanks for the informative post. Keep doing.
    dot-net-full-stack-developer-training-in-hyderabad

    ReplyDelete