To demonstrate how polymorphism works we need base class named Person.
class Person { public void showDescription() { System.out.println("I am Person"); } } // Class Boy extends class Person and override "showDescription()" method. class Boy extends Person { public void showDescription() { System.out.println("I am Boy"); } } // Class Girl extends class Person and override "showDescription()" method. class Girl extends Person { public void showDescription() { System.out.println("I am Girl"); } } // Class PersonService is used to do some action. // We print only kind of person. class PersonService { // Method agrument: object person public void showPersonDecription(Person person) { person.showDescription(); } } // Start program public class Main { public static void main(String[] args) { // Create three kinds of persons // Each object (p01, p02, p03) is assigned to class "Person". Person p01 = new Person(); Person p02 = new Boy(); Person p03 = new Girl(); /* print persons description */ new PersonService().showPersonDecription(p01); new PersonService().showPersonDecription(p02); new PersonService().showPersonDecription(p03); } }
Explanation:
There are two classes which extends basic class Person.
Then method showDescription() is overridden.
Class PersonService
Here is the key: Class PersonService has got one method which prints decription of given object of class Person (object of class Person, not class Boy or class Girl).
Class Main
Create three objects of class Person and pass it to the method of class PersonService.
TIP: Do you know that object is passed by reference? :)
Result of the program is:
I am Person I am Boy I am Girl
Polymorphism allows to work on the higher level of abstraction.
Now you can add new functionality to class Person and use it in every class which extends class Person.
You can simply add new class which extends class Person (for example class Baby) and don't have to change any functionality of class PersonService!
Reference:
Java official tutorial
No comments:
Post a Comment