1 / 34

Polymorphism and Type Casting Lecture

Learn about polymorphism and how it enables you to program in the general. Understand how polymorphism makes systems extensible and maintainable.

sharlenej
Download Presentation

Polymorphism and Type Casting Lecture

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 8 Polymorphism and Type Casting CSE 1322

  2. CSE 1322 Module A Quick Remainder

  3. OBJECTIVES The concept of polymorphism and how it enables you to “program in the general.” To use overridden methods to effect polymorphism. How polymorphism makes systems extensible and maintainable. To determine an object’s type at execution time.

  4. Introduction Polymorphism enables you to write applications that process objects that share the same base class in a class hierarchy as if they were all objects of the base class.

  5. Polymorphism promotes extensibility. • Software that invokes polymorphic behavior is independent of the object types to which messages are sent. • Only client code that instantiates new objects must be modified to accommodate new types.  Polymorphism

  6. Overloading vs Overriding

  7. Polymorphism Examples If class Rectangle is derived from class Quadrilateral, then a Rectangle is a more specific version of a Quadrilateral. Any operation that can be performed on a Quadrilateral object can also be performed on a Rectangle object. These operations also can be performed on other Quadrilaterals, such as Squares, Parallelograms and Trapezoids. The polymorphism occurs when an application invokes a method through a base-class variable.

  8. Polymorphism Examples As another example, suppose we design a video game that manipulates objects of many different types, including objects of classes Martian, Venusian, Plutonian, SpaceShip and LaserBeam. Each class inherits from the common base class SpaceObject, which contains method Draw. A screen-manager application maintains a collection(e.g., a SpaceObject array) of references to objectsof the various classes. To refresh the screen, the screen manager periodically sends each object the same message—namely, Draw, while each object responds in its own unique way.

  9. Polymorphic Behavior In a method call on an object, the type of the actual referenced object, not the type of the reference, determines which method is called. An object of a derived class can be treated as an object of its base class. The is-a relationship applies from a derived class to its direct and indirect base classes, but not vice versa. A base-class object is not an object of any of its derived classes.

  10. Polymorphism Requirements To use polymorphism, these conditions must be true: • the classes are in the same hierarchy. • all subclasses override the target method. • a subclass object reference is assigned to a superclass/base class object reference. • the superclass/base class object reference is used to call the target method.

  11. Polymorphic Behavior The compiler allows the assignment of a base-class reference to a derived-class variable if we explicitly cast the base-class reference to the derived-class type If an application needs to perform a derived-class-specific operation on a derived-class object referenced by a base-class variable, the base-class reference must be downcasted to a derived-class reference.

  12. Vehicle IS-A IS-A Understanding Object Relationship Car Truck IS-NOT-A

  13. // VehicleHierarchyEx1.java interface Vehicle{ booleanhasAnEngine= true; publicvoidvehicleInfo(); } class Car implements Vehicle { String vehicleInfo; intmaxSpeed; intmaxCapacity; Car(String carInfo){ this.vehicleInfo = carInfo; } @Override publicvoidvehicleInfo() { System.out.println("This is a " + this.vehicleInfo); } } class Truck implements Vehicle { String vehicleInfo; intmaxSpeed=0; intmaxLoad=0; Truck(String truckInfo){ this.vehicleInfo = truckInfo; } @Override publicvoidvehicleInfo() { System.out.println("This is a " + this.vehicleInfo); } } Understanding Object Relationship

  14. publicclass VehicleHierarchyEx1 { publicstaticvoid main(String[] args) { Car myCar1 = new Car("Toyota Camry 2016"); myCar1.vehicleInfo(); Car myCar2 = new Car("Maruti Swift 2015"); myCar2.vehicleInfo(); Truck myTruck1 = new Truck("Ford Focus-150 2016"); myTruck1.vehicleInfo(); } } Understanding Object Relationship Output: This is a Toyota Camry 2016 This is a Maruti Swift 2015 This is a Ford Focus-150 2016

  15. Vehicle IS-A IS-A Understanding Object Relationship Car Truck IS-NOT-A

  16. Engine HAS-A(n) HAS-A HAS-A Vehicle Understanding Object Relationship IS-A IS-A Car Truck IS-NOT-A

  17. Understanding Object Relationship

  18. Polymorphic Behavior When the compiler encounters a method call made through a variable, it determines if the method can be called by checking the variable’s class type. At execution time, the type of the object to which the variable refers determines the actual method to use.

  19. Implementing an interface C# public interface IMoveable{ void move (); void reverse (); } public class Player: IMoveable{ . . . public void move () { posX += 1; posY += 1; } public void reverse () { posX -= 1; posY -= 1; } }

  20. Using the interface polymorphically List <IMoveable> list = new List<IMoveable> (); list.Add (new Toy ("GI Joe", 5, 3)); list.Add (new Player ("Bill", 6, 4, 100)); foreach (IMoveable m in list) m.move (); foreach (IMoveable m in list) m.reverse (); Toy t; if (list [0] as Toy != null) { t = (Toy)list [0]; t.move (); }

  21. Implementing an interface Java public interface Moveable { public abstract avoid move (); //public and abstract allowed //but not required void reverse (); } public class Player implements Moveable { . . . public void move () { posX += 1; posY += 1; } public void reverse () { posX -= 1; posY -= 1; }

  22. Using the interface polymorphically ArrayList <Moveable> list = new List<Moveable> (); list.Add (new Toy ("GI Joe", 5, 3)); list.Add (new Player ("Bill", 6, 4, 100)); for (Moveable m : list) m.move (); for (Moveable m : list) m.reverse (); for(int i=0; i<list.size();i++) { if(list.get(i) instanceof Toy) { list.get(i).move(); System.out.println("moving a toy"); } } }

  23. UML The UML class diagram shows the inheritance hierarchy for a polymorphic employee payroll application.

  24. Assigning a base-class variable to a derived-class variable (without an explicit downcast) is a compilation error. • When downcasting, an InvalidCastException occurs if at execution time the object does not have an is-a relationship with the type specified in the cast operator. • An object can be cast only to its own type or to the type of one of its base classes. Common Programming Errors

  25. Engine Upcasting (By default) classVehcile{ voidvehicleInfo() {} } Type Cas t i ng Every Car IS-A Vehicle but Every Vehicle is NOT-A Car Inheritance Hierarchy and Object Type Casting Every Maruti IS-A Vehicle but Every Vehicle is NOT-A Maruti class Car extendsVehicle{ void carInfo() { super.vehicleInfo(); } } Every Maruti IS-A Vehicle but Every Vehicle is NOT-A Maruti Every Toyota IS-A Car but Every Car is NOT-A Toyota Every Maruti IS-A Car but Every Car IS-NOT-A Maruti No Totota is a Maruti class Toyota extends Car { @Override void carInfo() { } void toyotaSpecial() { } } class Maruti extends Car { @Override void carInfo() { } void toyotaSpecial() { } } Downcasting Figure: Inheritance Hierarchy and Object Type Casting

  26. Type Casting in Java Figure: Java wrapper class hierarchy

  27. A Type Casting Program in Java

  28. Engine Upcasting (By default) classVehcile{ voidvehicleInfo() {} } Type Cas t i ng Every Car IS-A Vehicle but Every Vehicle is NOT-A Car Inheritance Hierarchy and Object Type Casting Every Maruti IS-A Vehicle but Every Vehicle is NOT-A Maruti class Car extendsVehicle{ void carInfo() { super.vehicleInfo(); } } Every Maruti IS-A Vehicle but Every Vehicle is NOT-A Maruti Every Toyota IS-A Car but Every Car is NOT-A Toyota Every Maruti IS-A Car but Every Car IS-NOT-A Maruti No Totota is a Maruti class Toyota extends Car { @Override void carInfo() { } void toyotaSpecial() { } } class Maruti extends Car { @Override void carInfo() { } void toyotaSpecial() { } } Downcasting Figure: Inheritance Hierarchy and Object Type Casting

  29. Object UpCasting Examples

  30. Object UpCasting Examples Up-casting is easily doable (By default)

  31. DownCasting is Possible Using Object Reference Down-casting is difficult and a trouble maker

  32. Common Programming Error You can avoid a potential InvalidCastException by using the as operator to perform a downcast rather than a cast operator. If the downcast is invalid, the expression will be null instead of throwing an exception. Method GetType returns an object of class Type(of namespace System), which contains information about the object’s type, including its class name, the names of its methods, and the name of its base class. The Type class’s ToString method returns the class name.

  33. CSE 1321 Module 4 A Quick Remainder Test-1: 9/13/2018

  34. Common Programming Error You can avoid a potential InvalidCastException by using the instanceofoperator before performing a downcast

More Related