Understanding Polymorphism in Java Programming

object oriented programming concepts in java n.w
1 / 60
Embed
Share

Explore the concept of polymorphism in Java programming, including abstract methods, final methods, polymorphic behavior, and method calls. Learn about upcasting, downcasting, and compile-time method binding with practical examples and illustrations.

  • Java Programming
  • Polymorphism
  • OOP Concepts
  • Method Binding

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Object Oriented Programming Concepts in JAVA Polymorphism

  2. Agenda 2 Polymorphism Abstract method and Class Final Methods

  3. Animals can talk! 3

  4. Talk request 4 You can send a talk request to an animal What does it do? It depends on type of the animal

  5. Musical Instruments 5 The same note Different sounds on different instruments

  6. Polymorphic Behavior 6 Common interface The same request Different behaviors Depending on the type of object

  7. Polymorphism 7 The same interface animal.talk() instrument.play(int note) But different implementation in different classes

  8. Polymorphism 8 Suppose Child is a subclass of Parent class. Remember : A Child s object is also a Parent s object is-a relationship So these lines are valid: Child c = new Child(); Parent p = new Parent(); p = c; But this line is invalid: c = p;

  9. UpCasting 9 Upcasting Shape s = new Rectangle(); Circle c = new Circle(); Shape s = c; Upcasting is always valid

  10. DownCasting 10 Downcasting Shape s = Circle c = s; Circle c = (Circle) s; Needs type cast May cause errors

  11. What About Method Calls? 11 Shape s = new Rectangle(); s.draw(); double d = s.getArea(); Circle c = new Circle(); Shape s = c; s.draw(); double d = s.getArea();

  12. 12

  13. Compile-time Method Binding 13 Also known as Static Binding When a method is called, compiler knows which method is called The translation is done in compile-time

  14. Run-time Method Binding 14 Also known as Dynamic Binding When you call a method on a superclass reference Actual method is bound in runtime (If it is overridden) Performance overload

  15. Virtual Methods 15 In some languages (like C++) you can specify the binding mechanism for methods If a method is declared as virtual,dynamic binding is used for that method

  16. Applications of Polymorphism 16 Polymorphic behavior Suppose you have so many objects in a GUI application All of them have draw() operation You simply call draw() on every object It knows how to draw itself Classes : Drawable(superclass), Player, Referee, Ball,

  17. No Polymorphism 17

  18. With Polymorphism 18

  19. Hint on Array Initialization 19

  20. Animal Example 20

  21. 21 Cat & Dog

  22. Polymorphic Animals! 22

  23. Final in JAVA

  24. Final Methods 24 You can not override final methods final keyword Static method binding for final methods Private methods are implicitly final Static methods are implicitly final Static methods are statically bound Invoked reference is not important No polymorphism for static variables

  25. Final Variables 25 You can define variables as final The value of final variable will remain constant You can not change the value of final variables You should immediately assign a value to final variables Final parameter Final local variable Final property Final static variable

  26. Final Variables 26

  27. Final Classes 27 You can not inherit from final classes No class can extend final classes

  28. Review of final Keyword 28 Final data Const Local variables Method parameters Member variables Primitives constant values Objects constant references A compile-time constantthat won t ever change A value initialized at run time that you don t want changed

  29. Review of final Keyword (2) 29 Final Methods No override Final Class No sub-class final keyword on data Different from final classes & methods

  30. Finalism and Performance 30 Final methods can be invoked inline Compiler can bind final methods statically Static binding So it may bring a better performance It is now discouraged to use final to try to help the optimizer Especially with Java 6+ Don t worry about performance Java optimizer

  31. Final Classes final class Executive extends Manager { . . . }

  32. Final Methods You can also make a specific method in a class final. If you do this, then no subclass can override that method. (All methods in a final class are automatically final.) class Employee { . . . public final String getName() { return name; } . . . }

  33. More on Polymorphism

  34. class Parent{ public void f(){ } } class Child extends Parent{ public void f(){ System.out.println("f() in Child"); } } System.out.println("f() in Parent"); 34 public class SomeClass { public void method(Parent p){ System.out.println("method(Parent)"); } public void method(Child p){ System.out.println("method(Child)"); } }

  35. What is the output of: 35 Child child = new Child(); Parent parent = new Parent(); Parent parentRefToChild = new Child(); parent.f(); child.f(); parentRefToChild.f(); Output: f() in Parent f() in Child f() in Child

  36. What is the output of: 36 SomeClass square = new SomeClass(); square.method(parent); square.method(child); square.method(parentRefToChild); Output: method(Parent) method(Child) method(Parent) Important Note: Polymorphic behavior for reference the reference before dot Not for the parameters

  37. Note: Overloading 37 public class SomeClass { public void method(Parent p){ System.out.println("method(Parent)"); } public void method(Child p){ System.out.println("method(Child)"); } } method() is overloaded in SomeClass Two independent methods

  38. To Overload or to Override 38 class SomeClass { public void method(Parent p){ System.out.println("method(Parent)"); } } class SomeSubClass extends SomeClass{ public void method(Child p){ System.out.println("method(Child)"); } } method() is overloaded in SomeSubClass It is not overridden Two independent methods

  39. What is the output of: 39 SomeSubClass ref = new SomeSubClass(); ref.method(parent); ref.method(child); ref.method(parentRefToChild); Output: method(Parent) method(Child) method(Parent)

  40. A Question 40 When we override equals() method Why do we pass Object as the parameter? For example class Person has an equals method like this: public boolean equals(Object obj) { } But not like this: public boolean equals(Person obj) { } Why?!

  41. Abstract Classes

  42. Abstract Classes Java uses Abstract classes & Interfaces to further strengthen the idea of inheritance. To see the role of abstract of classes, suppose that the pay method is not implemented in the HourlyEmployee subclass. Obviously, the pay method in the Employee class will be assumed, which will lead to wrong result. One solution is to remove the pay method out and put it in another extension of the Employee class, MonthlyEmployee. The problem with this solution is that it does not force subclasses of Employee class to implement the pay method.

  43. Review of Abstract Classes (Cont'd) The solution is to declare the pay method of the Employee class as abstract, thus, making the class abstract. abstract class Employee { protected String name; protected double payRate; public Employee(String empName, double empRate) { name = empName; payRate = empRate; } public String getName() {return name;} public void setPayRate(double newRate) {payRate = newRate;} abstract public double pay(); public void print() { System.out.println("Name: " + name); System.out.println("Pay Rate: "+payRate); } }

  44. Review of Abstract Classes (Cont'd) The following extends the Employee abstract class to get MonthlyEmployee class. class MonthlyEmployee extends Employee { public MonthlyEmployee(String empName, double empRate) { super(empName, empRate); } public double pay() { return payRate; } } The next example extends the MonthlyEmployee class to get the Executive class.

  45. Review of Abstract Classes (Cont'd) class Executive extends MonthlyEmployee { private double bonus; public Executive(String exName, double exRate) { super(exName, exRate); bonus = 0; } public void awardBonus(double amount) { bonus = amount; } public double pay() { double paycheck = super.pay() + bonus; bonus = 0; return paycheck; } public void print() { super.print(); System.out.println("Current bonus: " + bonus); } } HourlyEmployee Employee Executive MonthlyEmployee

  46. Review of Abstract Classes (Cont'd) The following further illustrates the advantages of organizing classes using inheritance - same type, polymorphism, etc. public class TestAbstractClass { public static void main(String[] args) { Employee[] list = new Employee[3]; list[0] = new Executive("Jarallah Al-Ghamdi", 50000); list[1] = new HourlyEmployee("Azmat Ansari", 120); list[2] = new MonthlyEmployee("Sahalu Junaidu", 9000); ((Executive)list[0]).awardBonus(11000); for(int i = 0; i < list.length; i++) if(list[i] instanceof HourlyEmployee) ((HourlyEmployee)list[i]).addHours(60); for(int i = 0; i < list.length; i++) { list[i].print(); System.out.println("Paid: " + list[i].pay()); System.out.println("*************************"); } } } The Program Output

  47. Remember Animals Class Hierarchy 47

  48. Abstract Behaviors 48 Does any animal swim? No. So to swim is not a behavior of animals. Any animal has a voice to talk is a behavior of animals But what is the voice of an animal? How does an animal talk ? It depends to the specific type of animal Dog: Hop! Hop! Cat: Mewww!

  49. Abstract Behaviors (2) 49 talk is an abstract behavior of Animal All animals can talk But we can not specify how an animal talks It depends to the specific class of animal talk is a concrete behavior of Dog Hop! Hop! swim is not a behavior of Animal All animals can not swim swim is a concrete behavior of Fish

  50. Remember Shape Classes 50

Related


More Related Content