-1
class B{
    public void p(double i){
        System.out.println("B");
    }
}
class A extends B{
    public void p(double i){
        System.out.println("A");
    }
}


class Demo{
    public static void main(String args[]){
      //way of using polymorphic 1
        A a=new A();
        a.p(10.0);

      //way of using polymorphic 2
        A a=new B();
        a.p(10.0)
    }
 }

Both 2 ways provide same answer.But I want to know what is the difference between these 2 ways of using dynamic polymorphic.what is the best way to use in a program?

Malinda
  • 524
  • 2
  • 5
  • 11
  • The first example doesn't make use of polymorphism at all, so this appears to be a question of "should I use polymorphism / why use polymorphism / what is polymorphism good for" (ignoring the compiler errors for the time being). – Bernhard Barker Feb 04 '18 at 18:03
  • Related / maybe duplicate: [What is the real significance(use) of polymorphism](https://stackoverflow.com/q/2080020) – Bernhard Barker Feb 04 '18 at 18:06

2 Answers2

1

From the context and intent of polymorphism Your second way makes more sense.

Yohannes Gebremariam
  • 2,225
  • 3
  • 17
  • 23
0

If a method is overridden then in the run time the method of object type will be executed. Not the reference type.

Rumado
  • 165
  • 2
  • 16