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.
Java 8 update : Interface now contain default and static methods.
Choosing Between an Abstract Class and an Interface
Consider using abstract classes if any of these statements apply to your situation:
Consider using interfaces if any of these statements apply to your situation:
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!...
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!...
More about....Abstract class and Interface
ReplyDeleteLing
Abstraction in Java
ReplyDeleteReal 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.
Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
ReplyDeletejava training in chennai |
java training institutes in chennai
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.
ReplyDeletenice 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.
ReplyDeleteNice blog..! I really loved reading through this article... Thanks for sharing such an amazing post with us and keep blogging...
ReplyDeleteios app development course
thank you java training in chennai
ReplyDeletestruts training in chennai
core java training in chennai
Thanks for sharing this valuable information to our vision.
ReplyDeleteJava Online Training India
Thanks for sharing this valuable information to our vision.
ReplyDeleteJava Online Training India
The Blog Content is very informative and helpful. Please share more content. Thanks.
ReplyDeleteJAVA Training in Noida
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.
ReplyDeleteVisit 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
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.
ReplyDeleteCiitnoida 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
ReplyDeleteReally 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
CIIT Noida provides Best MCA Courses in Noida based on the current
ReplyDeleteIT 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
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
ReplyDeleteEach department of CAD have specific programmes which, while completed could provide you with a recognisable qualification that could assist you get a job in anything design enterprise which you would really like.
ReplyDeleteAutoCAD training in Noida
AutoCAD training institute in Noida
Best AutoCAD training institute in Noida
Cloud Computing Training In Noida
ReplyDeleteWebtrackker is IT based company in many countries. Webtrackker will provide you a real time projects based training on Cloud Computing. If you are looking for the Cloud computing training in Noida then you can join the webtrackker technology.
Cloud Computing Training In Noida , Cloud Computing Training center In Noida , Cloud Computing Training institute In Noida ,
Company Address:
Webtrackker Technology
C- 67, Sector- 63, Noida
Email: info@webtrackker.com
Website: www.webtrackker.com
http://webtrackker.com/Cloud-Computing-Training-Institutes-In-Noida.php
I am really happy with your blog because your article is very unique and powerful for new reader.
ReplyDeleteSelenium Training in Chennai | Selenium Training in Bangalore | Selenium Training in Pune
Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
ReplyDeletePython Training in electronic city
DataScience with Python Training in electronic city
AWS Training in electronic city
Big Data Hadoop Training in electronic city
Devops Training in electronic city
blockchain Training in electronic city
Hibernate Training in electronic city
Very Well! Great content, this is too helpful for us, Thanks for sharing this with us. Keep Sharing.
ReplyDeletejava training in yamunanagar
rpa training institute in noida
ReplyDeletesas training institute in noida
hadoop training institute in noida
blokchain traninig institute noida
servicenow scripting Training in Noida
ReplyDeleterpa training institute in noida
sas training institute in noida
hadoop training institute in noida
blokchain traninig institute noida
This is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.
ReplyDeleteiphone training institute in bangalore
best iphone training institute bangalore
ios app development in hyderabad
Like different elements of India, numerous oil and spices usually cross into making food. This effects in substances getting caught to the partitions of the filter out.
ReplyDeleteVisit here
http://kitchenware.ml
Best kitchen chimney installation and service
Auto clean chimney sevice in Faridabad
Nice Blog..It was so informative and usefull..Keep update. selenium training in chennai
ReplyDeleteselenium training in velachery
Nice blog..well explained abstract class it was very useful.Thank you..Hadoop Training in Chennai
ReplyDeleteExcellent article!!! Good work, your concept is really helpful for me. Thanks for your contribution in sharing such wonderful information.
ReplyDeleteJava Training Institute in Noida
Its really nice and informative.. Thanks for sharing
ReplyDeleteMicrosoft Azure Training institute in Noida,
AWS Training Institute in Noida sector 16,
Cloud Computing Training Institute in noida sector 16,
Data science training institute in noida sector 16,
Data Science With machine learning training Institute in Noida sector 16,
Data Science With python training Institute in Noida sector 16,
Web-designing Training Institute in Noida sector 16,
Its really nice and informative.. Thanks for sharing
ReplyDeletesoftware-testing Training Institute in Noida sector 16,
Digital Marketing Training Institute in noida sector 16,
hadoop Training Institute in noida sector 16,
Java Training Institute in noida sector 16,
linux Training Institute in noida sector 16,
node.js Training Institute in noida sector 16,
openstack Training Institute in noida sector 16,
Oracle DBA Training Institute in noida sector 16,
Its really nice and informative.. Thanks for sharing
ReplyDeletePhp Training Institute in noida sector 16,
PlSql Training Institute in Noida sector 16,
Python Training Institute in Noida sector 16,
RPA Training Institute in Noida sector 16,
Salesforce Training Institute in Noida sector 16,
Sap fico Training Institute in Noida sector 16,
ERP Sap mm Training Institute in Noida Sector 16,
Sap Training Institute in Noida Sector 16,
SAS Training Institute in Noida Sector 16,
Blue Prism Training Institute in Noida,
ReplyDeleteThanks 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