0

Java Polimorphism Lesson

Why bother defining the makeSound method in the super class? If you are defining it in every subclass of the super class I see no reason to bother defining it in the super class assuming that every subclass will have a different implementation of the method. In this case wouldn't doing the same code shown in the lesson, but without defining the method inside the super class do the same thing anyway?

11th Oct 2020, 3:37 AM
Dragon11705
Dragon11705 - avatar
1 Odpowiedź
+ 3
Then you are questioning the idea of polymorphism itself. Overriding being a runtime polymorphism allows you to give a new implementation of your own to the method in sub class. Animal dog = new dog(); dog.makeSound(); // the above line throws an error if the method is not declared in the superclass Animal. You generally create a super class which generally holds methods for common implementation, but if you need to define a new method in the subclass then you can do that. You can also create an abstract superclass which doesn't define the method and just declares it. abstract class Animal{ public abstract makeSound(); } And now give your own implementation in the consecutive subclasses.
11th Oct 2020, 5:30 AM
Avinesh
Avinesh - avatar