Presentation is loading. Please wait.

Presentation is loading. Please wait.

Polymorphism and Type Casting

Similar presentations


Presentation on theme: "Polymorphism and Type Casting"— Presentation transcript:

1 Polymorphism and Type Casting
Lecture 8 Polymorphism and Type Casting CSE 1322 4/26/2018

2 CSE 1322 Module A Quick Remainder 2/15/2019

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/26/2018

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. 4/26/2018

5 Polymorphism 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. 4/26/2018

6 Overloading vs Overriding
4/26/2018

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. 4/26/2018

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 objects of 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. 4/26/2018

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. 4/26/2018

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. 4/26/2018

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. 4/26/2018

12 Understanding Object Relationship
IS-A Vehicle Car Truck IS-NOT-A 4/26/2018

13 Understanding Object Relationship
// VehicleHierarchyEx1.java interface Vehicle{ boolean hasAnEngine= true; public void vehicleInfo(); } class Car implements Vehicle { String vehicleInfo; int maxSpeed; int maxCapacity; Car(String carInfo){ this.vehicleInfo = carInfo; @Override public void vehicleInfo() { System.out.println("This is a " + this.vehicleInfo); class Truck implements Vehicle { int maxSpeed=0; int maxLoad=0; Truck(String truckInfo){ this.vehicleInfo = truckInfo; 4/26/2018

14 Understanding Object Relationship
public class VehicleHierarchyEx1 { public static void 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 "); myTruck1.vehicleInfo(); } Output: This is a Toyota Camry 2016 This is a Maruti Swift 2015 This is a Ford Focus 4/26/2018

15 Understanding Object Relationship
IS-A Vehicle Car Truck IS-NOT-A 4/26/2018

16 Understanding Object Relationship
Engine HAS-A Vehicle IS-A Car Truck IS-NOT-A HAS-A(n) 4/26/2018

17 Understanding Object Relationship
4/26/2018

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. 4/26/2018

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; 4/26/2018

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 (); m.reverse (); Toy t; if (list [0] as Toy != null) { t = (Toy)list [0]; t.move (); } 4/26/2018

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; 4/26/2018

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 (); 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"); } } } 4/26/2018

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

24 Common Programming Errors
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. 4/26/2018

25 Inheritance Hierarchy and Object Type Casting
class Vehcile{ void vehicleInfo() {} } Upcasting (By default) Type Cas t i ng Downcasting Every Car IS-A Vehicle but Every Vehicle is NOT-A Car class Car extends Vehicle{ void carInfo() { super.vehicleInfo(); Every Maruti IS-A Vehicle but Every Vehicle is NOT-A Maruti Every Maruti IS-A Vehicle but Every Vehicle Engine 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 Maruti extends Car { @Override void carInfo() { } void toyotaSpecial() { } class Toyota extends Car { Figure: Inheritance Hierarchy and Object Type Casting 4/26/2018

26 Type Casting in Java Figure: Java wrapper class hierarchy 4/26/2018

27 A Type Casting Program in Java
4/26/2018

28 Inheritance Hierarchy and Object Type Casting
class Vehcile{ void vehicleInfo() {} } Upcasting (By default) Type Cas t i ng Downcasting Every Car IS-A Vehicle but Every Vehicle is NOT-A Car class Car extends Vehicle{ void carInfo() { super.vehicleInfo(); Every Maruti IS-A Vehicle but Every Vehicle is NOT-A Maruti Every Maruti IS-A Vehicle but Every Vehicle Engine 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 Maruti extends Car { @Override void carInfo() { } void toyotaSpecial() { } class Toyota extends Car { Figure: Inheritance Hierarchy and Object Type Casting 4/26/2018

29 Object UpCasting Examples
Statements with UpCasting Effect Toyota carref1 ; carref1 = new Toyota(); The carref1 is a run-time object of : class Toyota Is carref1 an instance of Car? true Is carref1 an instance of Toyota? true carref1.vehicleInfo(); Invokes Vehicle::vehicleInfo() ((Car)carref1).vehicleInfo(); ((Toyota)carref1).vehicleInfo(); Still Invokes Vehicle::vehicleInfo() ((Car)((Toyota)carref1)).vehicleInfo(); ((Toyota)((Car)((Toyota)carref1))).vehicleInfo(); carref1.carInfo(); Invokes Toyota::carInfo() ((Car)carref1).carInfo(); ((Toyota)carref1).carInfo(); ((Car)((Toyota)carref1)).carInfo();a ((Toyota)((Car)((Toyota)carref1))).carInfo(); 4/26/2018

30 Object UpCasting Examples
Statements with UpCasting Effect carref1.toyotaSpecial(); Invokes Toyota::toyotaSpecial() ((Car)carref1).toyotaSpecial(); Shows Compile-time Error ‘The method toyotaSpecial() is undefined for the type Car’ ((Toyota)carref1).toyotaSpecial(); //((Car)((Toyota)carref1)).toyotaSpecial(); ((Toyota)((Car)((Toyota)carref1))).toyotaSpecial(); Invokes Vehicle::vehicleInfo() Toyota carref1 = new Car(); // NOT allowed. Shows follwong ERROR ‘Type mismatch: cannot convert from Car to Toyota’ Toyota carref = new Vehicle(); // Cannot instantiate the type Vehicle // Because Vehicle is an Abstract Class Toyota carref = new Maruti(); // Type mismatch: cannot convert from Maruti to Toyota Up-casting is easily doable (By default) 4/26/2018

31 DownCasting is Possible Using Object Reference
Statements with DownCasting Effect Car carref1; carref1 = new Toyota(); The carref1 is a run-time object of : class Toyota Is carref1 an instance of Car? true Is carref1 an instance of Toyota? true Is carref1 an instance of Maruti? false //carref1.toyotaSpecial(); Shows following Compile-time Error ‘The method toyotaSpecial() is undefined for the type Car’ ((Toyota)carref1).toyotaSpecial(); Works good, DownCasting Invokes Toyota::toyotaSpecial() ((Car)carref1).toyotaSpecial(); Shows Compile-time Error //((Car)((Toyota)carref1)).toyotaSpecial(); Shows Compile-time Error ‘The method toyotaSpecial() is undefined for the type Car’ ((Toyota)((Car)((Toyota)carref1))).toyotaSpecial(); DownCasting Works good, Car carref1 = (Toyota) new Car(); // Allowed at compile time; but wills show an but will show follwing Runtime ERROR 'Car cannot be cast to Toyota' Down-casting is difficult and a trouble maker 4/26/2018

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. 4/26/2018

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

34 Common Programming Error
You can avoid a potential InvalidCastException by using the instanceof operator before performing a downcast 4/26/2018


Download ppt "Polymorphism and Type Casting"

Similar presentations


Ads by Google