Polymorphism Flashcards
What is Polymorphism?
Poly=many morph=forms
Why Polymorphism?
Polymorphism lets programmers sacrifice specificity for generality and treat any number of classes as their lowest common denominator and limited to methods declared in that denominator.
What is Dynamic Binding?
Dynamic binding, which is when actual method implementation used is not determined until runtime and in contrast with static binding, in which method gets resolved at compile time
Why Declared Type?
declared type keeps things generic and can reference a lot of objects using one generic type
Why Actual Type?
Actual type ensures specificity and when defining implementing class, the method can get implemented in any way
Inheritance models, which relationship?
Inheritance models “is a” relationship
Interface models “acts as” relationship
Is multiple inheritances allowed in java?
No, in java you can only inherit from one superclass due to the diamond problem.
Types of polymorphism
In Java polymorphism is mainly divided into two types:
Compile-time Polymorphism
Runtime Polymorphism
Compile Time Polymorphism
It is also known as static polymorphism. This type of polymorphism is achieved by function overloading.
Functions can be overloaded by a change in the number of arguments or/and a change in the type of arguments.
Runtime Polymorphism
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime.
This type of polymorphism is achieved by Method Overriding.
Runtime Polymorphism (data members)
In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be achieved by data members. For example : class A { int x = 10; }
// class B class B extends A { int x = 20; }
// Driver class public class Test { public static void main(String args[]) { A a = new B(); // object of type B
// Data member of class A will be accessed System.out.println(a.x); //10 } }
Static vs Runtime Binding
Static binding is done during compile-time while the dynamic binding is done during run-time.
private, final, and static methods and variables use static binding and bonded by the compiler while overridden methods are bonded during runtime based upon the type of runtime object