Wednesday, August 24, 2016

Inheritance, Interface, Composition and Multiple Inheritance In Java

Inheritance : 
  • Core OOPS concept.
  • Is-a relationship with objects
  • "Extends" is used
  • Transitive in nature A-->B B-->C  A-->C

Interface:
  • 'interface' word used to define interface
  • can't instantiate interface so constructors not allowed in interface
  • methods can be defined but not implemented in interface i.e. can't have a body. by default menthods are public and abstract
  • by default any attribute of interface is public, static and final even if no access modifier is defined
  • can't extend a class but can extend 1/many interfaces. extends is the keyword used
  • implements keyword is used to implement an interface.
  • Once a class implements all methods should be implemented. Implemented class can define its own methods
Benefits of interface:
  • Implementation class can't remove the methods defined in interface so it acts as a contract
  • can act as Type and helpful in defining top level hierarchy
  • class can implement multiple interfaces, so interface acts as better super class

Composition:
  • Has-a relationship
Multiple Inheritance:
  • Not supported in Java Classes as it can lead to diamond problem. Superclass A is abstract with method test(). A is inherited by B and C hence test() is defined. Now, if D extends both B and C and test() method is invoked in D, the compiler gets confused which is known as diamond problem.
  • Supported in Java Interfaces. A single interface can 'extends' multiple interfaces
  • Java class can 'implements' multiple interfaces
  • when overriding any superclass method or implementing any interface method use @Override notation
  • public class InterfaceImpl implements InterfaceA, InterfaceB --> valid
  • public interface extends InterfaceA, InterfaceA --> Valid
  • If methods from different classes need to be utilized, we can use composition by defining the class object and using the method.
Problems with Inheritance:
  • Methods need to be the same can't change return type etc.
  • all superclass methods are exposed to client which could lead to security issues if super class not designed properly
  • Unit testing a bit difficult and we need to test all methods of super class