+ 1

Explain run time and compile time polymorphism!!

polymorphism

22nd Jun 2018, 7:50 PM
Aahnik Daw
Aahnik Daw - avatar
3 odpowiedzi
+ 3
Method overloading is compile time, because at compile time we can select which method we are using. Because Java is strongly typed, we know which method we're referring to (e.g. method(int i) or method(double d) ) Runtime happens because the runtime type of an object is needed to select which implementation to use (overriding) e.g. abstract class Animal { void makeSound(); } class Cat extends Animal { void makeSound() { // meow } } class Dog extends Animal { void makeSound() { // woof } } if we declare a variable Animal a = getAnimal (); where we retrieve an animal somehow, only at runtime will the program know which implementation to use. Depends on the runtime type of the object :)
22nd Jun 2018, 8:10 PM
Dan Walker
Dan Walker - avatar
+ 1
i cannot understand overriding plz explain
23rd Jun 2018, 1:30 AM
Aahnik Daw
Aahnik Daw - avatar
+ 1
Cat and Dog both override/implement the makeSound method. In the code all I know is that I'll get an Animal, so it can makeSound() but I don't know which one I'll get. When I actually get an object, it will be an actual animal type, and the particular method invoked will be of the class type I have. That is basically overriding
23rd Jun 2018, 7:33 AM
Dan Walker
Dan Walker - avatar