Saturday, 16 February 2019

Polymorphism

Polymorphism - Many forms


There are two components of Polymorphism
  1. code is dependent on an interface/parent class
  2. behavior of code is determined at runtime by the actual class implementing that interface/parent class
Hence, we can define polymorphism as - the ability, at run time or dynamically, for that code to be able to call whatever method is implemented by the class that inherits from the base class.

The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). 

As overriding depends on having an instance of a class, a static method is not associated with any instance of a class - so the concept is not applicable for static methods.

Polymorphism is categorized in two forms
  1. static polymorphism - Enforced at compile time; eg method overloading, operator overloading
  2. dynamic polymorphism - Realization done at runtime; eg method overriding, concept of variable hiding

How Polymorphism works

  • This occurs in classes which have an Is-A relationship, where the subclass overrides the behavior of the parent class and at runtime, the JVM dynamically changes the behavior
  • Dynamic polymorphism is exhibited only in the objects behavior i.e. the methods, and NOT on the 
    • state of the object
    • behavior of the class
  • If we define a member variable again in the subclass, then it would not be overriding the value from the parent, this phenomenon is referred to as hiding. The subclass will have access to both the variables (will have two variables with same name), but depends on how it would be accessed and it would be enforced at compile time rather than runtime. 
The above concepts have been demonstrated at below link.

https://github.com/omerhashmininjago/java-programs/tree/master/src/main/java/com/demonstrate/concepts/polymorphism/example1




No comments:

Post a Comment

Volatile keyword, Synchronized keyword and Lock interface

Volatile Marking a member variable as volatile, makes sure, when ever the member variable is accessed, its value is always read from the...