That’s all about polymorphism I want to share with you today. Snake, we just pass an object of Snake into the teach() method without any modification. Extensibility: when we want to add a new kind of Animal, e.g.Flexibility: the actual object can be determined at runtime which allows the code run more flexibly.Reusability: the teach() method can be re-used for different kinds of objects as long as they are sub types of the Animal interface.It increases the reusability, flexibility and extensibility of code. Why is Polymorphism?Polymorphism is a robust feature of OOP. Thus we see the outputs: Running… (from the Dog object). And depending on the actual object type, the appropriate overriding method is called. Swimming…Here, as you can see, the teach() method can accept ‘many forms’ of Animal: Dog, Bird, Fish,… as long as they are sub types of the Animalinterface.In the teach() method, the move() method is invoked on the Animal reference. For example: Trainer trainer = new Trainer() If an object of a derived class is assigned to a variable whose type is that of further up the same class hierarchy, this is called upcasting. Thus we can pass any objects which are sub types of the Animaltype. How is Polymorphism Implemented in Java?In Java, you can implement polymorphism if you have a super class (or a super interface) with two or more sub classes.Let’s understand by looking at some examples.Suppose that we have the following interface and classes: public interface Animal Notice that the teach() method accepts any kind of Animal. You will understand polymorphism quickly.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |