Wednesday, April 3, 2019

Java Interview Questions Part-4

1.  Inheritance Vs Composition in java

Inheritance Composition
 Inheritance maintain “is-a” relationship between a given   class and others.  Composition maintain “has-a” relationship
 between a given class and others.
 Inheritance is tightly coupled.
 Example employee is person.
 Composition is loosely coupled.
 Static vs Dynamic :
 From flexibility point of view - once extends,
 we can not change the implementation of class.
 we can just define the type which may hold   multiple implementation, that we can provide at   runtime. So this is much flexible than Inheritance. 
 Limited code reuse with Inheritance : 
 We can extend only one class. That means we can
 reuse  only one class functionality not more than one.
 we can get leverage functionalities from multiple
 class by using composition. As mention above   point.
 Unit Testing :
 We must need parent class to test child class. this is   difficult to test.
 This is easy to test by mock implementation of   dependent classes
 Use of Final classes :
 We can't extends final class.
 We can use final class by using composition.
 Encapsulation and robustness point of view :
 Inheritance breaks encapsulation that means any   changes into any method would affect to subclass.
 Maintain the  encapsulation.
Access control in inheritance :
 There is no access control in inheritance. Suppose add   new public method in parent class then it will be   accessible to subclass. 
 We have complete access controls in composition.
 In composition we choose which methods to use,   it's more secure than inheritance.






Related Tutorials



No comments:

Post a Comment