You are on page 1of 3


Why Favor Composition over Inheritance in Java and Object Oriented Programming

Blog about Java Program Tutorial Example How to, Unix Linux commands, Interview Questions, FIX Protocol, Tibco RV tutorials, Equities trading system, MySQL

Java Java
T UES DA Y , J UNE 4, 2013

Java Software

Java Test Tool

Program Java
Searc h

Why Favor Composition over Inheritance in Java and Object Oriented Programming
Favor composition over inheritance is a one of the popular object oriented design principle, which helps to create flexible and maintainable code in Java and other object oriented languages. Many times I have seen people suggesting use composition instead of inheritance, in fact my favorite books like Head first Design Patterns, also advocates this design principle. Head first books, has its own way of explaining, why composition is better than inheritance and though its long its quite interesting and informative. It was the first chapter of this book, which helped me a lot on understanding this key OOPS concept. In this Java and OOPS tutorial, I have tried to summarize my experience around composition and inheritance in two main category, first, difference between composition and inheritance and second, when to use Composition over inheritance in Java. I have already mentioned about this design principle, in my list of 10 OOPS and SOLID design principles for Java programmers, here we will take a more closer look.

Recent Posts

When to make a method static in Java Top 5 JQuery books for Beginners and Web developers - Best of lot How SSL, HTTPS and Certificates works in Java web applications Role based Access control using Spring Security and MVC, Mapping LDAP Groups to Authorities for Authorization 10 Java Exception and Error Interview Questions Answers 5 must read books to learn Object Oriented and Java Design patterns - Best of lot

Reasons to prefer Composition over Inheritance in Java

Just to revise, composition and Inheritance are ways to reuse code to get additional functionality. In Inheritance, a new class, which wants to reuse code, inherit an existing class, known as super class. This new class is then known as sub class. On composition, a class, which desire to use functionality of an existing class, doesnt inherit, instead it holds a reference of that class in a member variable, thats why the name composition. Inheritance and composition relationships are also referred as IS-A and HAS-A relationships. Because of IS-A relationship, an instance of sub class can be passed to a method, which accepts instance of super class. This is a kind of polymorphism, which is achieved using Inheritance. A super class reference variable can refer to an instance of sub class. By using composition, you dont get this behavior, but still it offers a lot more to tild the balance in its side. 1) One reason of favoring Composition over Inheritance in Java is fact that Java doesn't support multiple inheritance. Since you can only extend one class in Java, but if you need multiple functionality like e.g. for reading and writing character data into file, you need R e a d e rand W r i t e rfunctionality and having them as private members makes your job easy. Thats called composition. If you are following programming for interface than implementation principle, and using type of base class as member variable, you can use different R e a d e rand W r i t e rimplementation at different situation. You wont get this flexibility by using Inheritance, in case of extending a class, you only get facilities which are available at compile time. 2) Composition offers better testability of a class than Inheritance. If one class is composed of another class, you can easily create Mock Object representing composed class for sake of testing. Inheritance doesn't provide this luxury. In order to test derived class, you must need its super class. Since unit testing is one of the most important thing to consider during software development, especially in test driven development, composition wins over inheritance. 3) Many object oriented design patterns mentioned by Gang of Four in there timeless classic Design Patterns: Elements of Reusable Object-Oriented Software, favors Composition over Inheritance. Classical examples of this is S t r a t e g y design pattern, where composition and delegation is used to change Contexts behavior, without touching context code. Since Context uses composition to hold strategy, instead of getting it via inheritance, its easy to provide a new Strategy implementation at runtime. Another good example of using composition over inheritance is D e c o r a t o rdesign pattern. In Decorator pattern, we don't extend any class to add additional functionality, instead we keep an instance of the class we are decorating and delegates original task to that class after doing decoration. This is one of the biggest proof of choosing composition over inheritance, since these design patterns are well tried and tested in different scenarios and withstand test of time, keeping there head high. 4) Though both Composition and Inheritance allows you to reuse code, one of the disadvantage of Inheritance is that it breaks encapsulation. If sub class is depending on super class behavior for its operation, it suddenly becomes fragile. When behavior of super class changes, functionality in sub class may get broken, without any change on its part. One example of inheritance making code fragile is method a d d ( )and a d d A l l ( )from HashSet. Suppose, If a d d A l l ( )of HashSet is implemented by calling a d d ( )method and you write a sub class of HashSet, which encrypt the content before inserting into HashSet. Since there are only one methods a d d ( ) ,which can insert object into HashSet you override these method and called your e n c r y p t ( )method by overriding a d d ( ) . This automatically covers a d d A l l ( )as well, because a d d A l l ( )is implemented using add(), it looks very enticing. If you look closely you will see that this implementation is fragile, because its relied on super class behavior. If base class wants to improve performance and implements a d d A l l ( )without calling a d d ( )method, below example will break.

Follow Us
Follow @javinpaul 3,239 follow ers

Javarevisited on





Why Favor Composition over Inheritance in Java and Object Oriented Programming
p u b l i cc l a s sE n c r y p t e d H a s h S e te x t e n d sH a s h S e t { . . . . . p u b l i cb o o l e a na d d ( O b j e c to ){ r e t u r ns u p e r . a d d ( e n c r y p t ( o ) ) ; } }
If you have used Composition in favor of Inheritance you won't face this problem and your Class would have been more robust, because you are not relying on super class behavior any more. Instead you are using super class method for addition part and you will benefit with any improvement in a d d A l l ( )as shown in below example:

p u b l i cc l a s sE n c r y p t e d H a s h S e ti m p l e m e n t sS e t { p r i v a t eH a s h S e tc o n t a i n e r ; p u b l i cb o o l e a na d d ( O b j e c to ){ r e t u r nc o n t a i n e r . a d d ( e n c r y p t ( o ) ) ; } p u b l i cb o o l e a na d d A l l ( C o l l e c t i o nc ){ r e t u r nc o n a t a i n e r . a d d ( e n c r y p t ( c ) ) ; }

Like 4,660 people like Javarevisited.

F acebook social plugin

. . . . . . . }
5. Another reason of favoring Composition over inheritance is flexibility. If you use Composition you are flexible enough to replace implementation of Composed class with better and improved version. One example is using Comparator class which provides compare functionality. if your Container object contains a C o m p a r a t o rinstead of extending a particular C o m p a r a t o rfor comparing , its easier to change the way comparison is performed by setting different type of C o m p a r a t o rto composed instance, while in case of inheritance you can only have one comparison behavior on runtime, You can not change it runtime. There are many more reasons to favor Composition over inheritance, which you will start discovering once you start using design patterns in Java. In nutshell favoring Composition results in more flexible and robust class than using inheritance. Though there are certainly some cases where using Inheritance makes much sense like when a genuine parent child relation exists, but most of time it makes sense to favor composition over inheritance for code reuse. There is an item of this topic on my another favorite book, Effective Java, which has also helped me to understand this concept better, you may want to look that as well. Related Java design pattern and best practices tutorials from Javarevisited Blog Top 10 JDBC best practices for Java programmers Java tips to avoid NullPointerException and minimize null checks How to use Builder design pattern in Java 10 Java Exception handling best practices for Java programmers Difference between overloading and overriding in Java

Recommendd Books Java Programming and Design Pattern Spring Framework Subscribe by email: Subscribe By Javin Paul Subscribe To This Blog Free Posts Comments Followers Join this site
w ith Google Friend Connect

Members (1250) More

Please share with your friends if like this article

Already a member? Sign in

Composition over inheritance

You might like:


Performance Review


Java Software Development Java Programming Examples Java Sample Programs

Blog Archive 2013 (97) July (4)
Recommended by

How to get current URL, parameters and Hash tag using JQuery and JavaScript How to Generate MD5 checksum for Files in Java Javarevisited: FIX Protocol, tibco,unix and java tutorial with example Why Enum Singleton are better in Java

June (9) 10 Java Exception and Error Interview Questions An... 5 must read books to learn Object Oriented and Jav... Introduction of How Android Works for Java Program... How to Add Two Integer Numbers without using Plus ... Spring HelloWorld Example in Java using Dependency...

Posted by Javin Paul at 8:24 AM

+16 Recommend this on Google

Labels: best practices, core java, design patterns, programming

Builder Design Base Class



You can only Examples

Inheritance in java Performance Review

Composition over inheritance

1 comment:


Gauri said...

Why Favor Composition over Inheritance in Java and Object Oriented Programming
Favor Composition because it adds functionality at runtime, while Inheritance adds functionality at compile time. June 26, 2013 at 8:18 PM How to Generate MD5 checksum for Files in Java How to get current URL, parameters and Hash tag us... Why Favor Composition over Inheritance in Java and... How to find CPU and Memory used by Java process in... May (14) April (18) March (16) February (18) January (18) 2012 (218)

Post a Comment
E n t e ry o u rc o m m e n t . . .

Comment as: Google Account Publish Preview

2011 (145) 2010 (33)

References Java API documentation JDK 6 Newer Post Subscribe to: Post Comments (Atom) Home Older Post Spring framework doc Struts ANT Maven JDK 7 API MySQL Linux Eclipse Copyright by Javin Paul 2012. Powered by Blogger.

About Me

Privacy Policy