Wagee_CDR Wagee_CDR - 1 month ago 5
Java Question

Java : difference between runtime polymorphism and normal situation when creating objects

Here I have this question. Let's say code 1 is Java with runtime polymorphism and code 2 is Java without runtime polymorphism.

Code 1:

class A {
void run() { System.out.println("A is running"); }
}

class B extends A{
void run(){ System.out.println("B is running with A!");}

public static void main(String args[]){

A a = new B(); //referenced to class A
a.run();

}
}


Code 2:

class A {
void run(){System.out.println("A is running");}
}

class B extends A{
void run(){ System.out.println("B is running with A!");}

public static void main(String args[]){
B a = new B(); //referenced to the same constructor class
a.run();
}
}


Even though these two codes give the exact same results, it is well known that runtime polymorphism is really important in OOP. I need an explanation/reason of using code 1 instead of using code 2.

Answer

Using a polymorphism is not mandatory in OOP.
Polymorphism is a mechanism which brings flexibility when flexibility is needed.

For example, in your case, writing :

B a = new B();

or

A a = new B()

depends if you need and have interest to reference the base class rather than the subclass as declared type for your variable.

Referencing the base class (here A) allows many things among these important points :

  • masking the implementation (via factory or injection dependency). In this way, you can change the implementation (returning a C or D which extends A) without breaking calls of client code. In your code, you don't perform that but in real applications you can have this need.
  • If you have processings common to A and B classes, you may propose a method which takes as parameter a instance of type A. Example : public void doProcess(A instance)
    In this case, if you declare B a = new B(), the code will not compile if you pass this instance to that method as semantically, a B instance is a A but a A instance is not necessarily a B

Often, we can read that declaring the interface rather that the implementation is a good practice. In fact, it is in most of cases but in some other cases, it is not. Just one example, if you need to use a TreeMap, you will not declare the interface Map because the behavior of TreeMap is very specific and have special requirements, so you may want to stress on. When you instantiate a classic HashMap, generally, you don't care precising in the declaration type it is a HashMap since it is a classic.

Comments