ploy morph ism

Upload: juan-cristobal

Post on 10-Apr-2018

227 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/8/2019 Ploy Morph Ism

    1/32

    Polymorphism

  • 8/8/2019 Ploy Morph Ism

    2/32

    Lecture Objectives

    To understand the concept ofpolymorphism

    To understand the concept ofstatic orearlybinding

    To understand the concept ofdynamic orlatebinding

  • 8/8/2019 Ploy Morph Ism

    3/32

    Polymorphism

    Polymorphism comesfrom Greek meaning manyforms.

    In Java, polymorphismrefers to the dynamic bindingmechanism that determines whichmethod definitionwill be used when a method name has beenoverridden.

    Thus, polymorphismrefers todynamic binding.

  • 8/8/2019 Ploy Morph Ism

    4/32

    Polymorphism (Contd)

    Can treat an object ofa subclass as an object ofitssuperclass A reference variable of a superclass type can point to an

    object of its subclass

    Person name, nameRef;PartTimeEmployee employee, employeeRef;name = new Person("John", "Blair");employee = new PartTimeEmployee("Susan", "Johnson",

    12.50, 45);nameRef= employee;System.out.println("nameRef: " + nameRef);

    nameRef: Susan Johnson wages are: $562.5

  • 8/8/2019 Ploy Morph Ism

    5/32

    Polymorphism (Contd)

    Late binding ordynamic binding (run-timebinding): Method to be executed is determined at execution

    time, not compile time

    Polymorphism: to assign multiple meaningsto the same method name

    Implemented using late binding

  • 8/8/2019 Ploy Morph Ism

    6/32

    Polymorphism (Contd)

    The reference variable name ornameRef can pointto anyobject ofthe class Person orthe classPartTimeEmployee

    These reference variableshave manyforms, thatis, they are polymorphic reference variables

    They can refertoobjectsoftheirown classortoobjectsofthe classesinherited from theirclass

  • 8/8/2019 Ploy Morph Ism

    7/32

    Polymorphism (Contd)

    Can declare a method ofa classfinal using thekeyword final

    Ifa method ofa class is declared final, itcannot be overridden with a new definition in aderived class

    public final void doSomeThing(){//...

    }

  • 8/8/2019 Ploy Morph Ism

    8/32

    Polymorphism (Contd)

    Can also declare a class final using the keywordfinal

    Ifa class is declared final, then nootherclass

    can be derived from this class

    Java does not use late binding formethods thatareprivate, marked final, orstatic

  • 8/8/2019 Ploy Morph Ism

    9/32

    Polymorphism (Contd)

    You cannot automaticallymake reference variableofsubclass type point toobject ofitssuperclass

    Suppose that supRef is a reference variable ofasuperclass type and supRef points to an object ofitssubclass:

    Can use a cast operator on supRef and make a referencevariable of the subclass point to the object

    IfsupRef does not point to a subclass object and you use a

    cast operator on supRef to make a reference variable of thesubclass point to the object, then Java will throw aClassCastExceptionindicating that the class cast is notallowed

  • 8/8/2019 Ploy Morph Ism

    10/32

    Polymorphism (Contd)

    Operatorinstanceof: determines whetherareference variable that points to an object isofaparticularclass type

    This expression evaluates totrue ifp points to anobject ofthe class BoxShape;otherwise itevaluates tofalse

    pinstanceofBoxShape

  • 8/8/2019 Ploy Morph Ism

    11/32

    Polymorphism (Contd)

    Interface variable holdsreference toobject ofa class that implements the interfaceMeasurable x;

    Note that the object to whichx refers doesn'thave typeMeasurable; the type ofthe object

    issome class that implements theMeasurable interface

    Continued

    x = new BankAccount(10000);

    x = new Coin(0.1, "dime");

  • 8/8/2019 Ploy Morph Ism

    12/32

    Polymorphism (Contd)

    You can call anyofthe interface methods:

    Whichmethod is called?

    double m = x.getMeasure();

  • 8/8/2019 Ploy Morph Ism

    13/32

    Polymorphism (Contd)

    Dependson the actualobject.

    Ifx refers to a bank account, calls

    BankAccount.getMeasure() Ifx refers to a coin, callsCoin.getMeasure()

    Polymorphism (manyshapes): Behaviorcan

    vary depending on the actual type ofan object

    Continued

  • 8/8/2019 Ploy Morph Ism

    14/32

    Polymorphism (Contd)

    Called late binding:resolved at runtime

    Different fromoverloading;overloading isresolved by the compiler(early binding)

  • 8/8/2019 Ploy Morph Ism

    15/32

    Dynamic Binding

    Different objects can invoke different method definitionsusing the same method name.

    The type ofobject being referenced at the time ofthemethod call, not the type ofreference that was declared,determines whichmethod isinvoked.

    Forexample, ifthe reference b references a Box object andthe reference t references a Triangle object, b and t invokedifferent definitionsofthe method drawAt() even ofb and tare declared to be oftype Figure.

  • 8/8/2019 Ploy Morph Ism

    16/32

    Dynamic Binding (Contd)

    Considerthe following example:

    Figure f;

    Box b = new Box(1, 4, 4);f= b;f.drawAt(2);Triangle t = new Triangle(1,2);f= t;f.drawAt(2);

  • 8/8/2019 Ploy Morph Ism

    17/32

    The method drawAt() isinherited from classFigureand is not overridden.

    But, method drawHere() isinvoked within the

    definition ofmethod drawAt(), and methoddrawHere() isoverridden.

    The type ofobject referred to byfdetermines whichmethod drawHere() isinvoked.

    Dynamic Binding (Contd)

  • 8/8/2019 Ploy Morph Ism

    18/32

    Type Checking and Dynamic Binding

    Recall that an object reference to an ancestorclass canreferto an object ofa descendant class.

    However, you can invoke only a method in classPerson

    with the variable p.

    Employee e = new Employee();Person p;p = e;

  • 8/8/2019 Ploy Morph Ism

    19/32

    However, ifa method isoverridden in the classEmployee, and variablep references an Employeeobject, then the method in classEmployee is used.

    The variable determines what methods can be used, butthe type referenced by the object determines whichdefinition ofthe method will be used.

    Type Checking and Dynamic Binding (Contd)

  • 8/8/2019 Ploy Morph Ism

    20/32

    Type Checking and Dynamic Binding (Contd)

    To use a method name in the classEmployee withan object named by the variablep oftype Person,

    use a type cast.

    Example:

    Employee e = (Employee)p;e.setEmployeeNumber(5678);

  • 8/8/2019 Ploy Morph Ism

    21/32

    However, even a type cast cannot fool Java!

    Example:

    will use the definition ofthe method drawHere() givenin classBox, not the definition ofdrawHere() given inclassFigure.

    Type Checking and Dynamic Binding (Contd)

    Box b = new Box (1, 4, 4);Figure f= (Figure)b;

    f. drawHere()

  • 8/8/2019 Ploy Morph Ism

    22/32

    You are unlikely to assign an object ofa descendanttype to a variable ofa parent type, at least not directly.

    But, such an assignment can occurindirectly byproviding an argument ofa descendant type foramethod that has a parameterofan ancestor type.

    Type Checking and Dynamic Binding (Contd)

  • 8/8/2019 Ploy Morph Ism

    23/32

    Dynamic Binding with the toString()

    Method

    Recall the method toString() typicallyis used toprepareand return a string, describing an object, foroutput tothe screen.

    The name ofthismethod can be omitted, thanks todynamic binding, because one definition ofmethod

    println() expects a single argument oftype Object whichit uses toinvoke the method toString() associated withthe object.

  • 8/8/2019 Ploy Morph Ism

    24/32

    Subtle Difference

    Dynamic binding refers to the process carried out by thecomputer.

    Polymorphism can be thought ofassomething objectsdo.

    Polymorphism, encapsulation, and inheritance, and

    considered to be the main featuresofobject-orientedprogramming.

  • 8/8/2019 Ploy Morph Ism

    25/32

    A Betterequals() Method

    Sometimes the method equals() from classObject isoverloaded when it should have been overridden.

    Thisoccurs when itsparameteris not oftype Object.

    Usually, thisis allright.

  • 8/8/2019 Ploy Morph Ism

    26/32

    A Betterequals() Method (Contd)

    But, ifthe method equals() is called with an object ofclassObject asits argument, the method equals()from classObject will be invoked.

    The problemisfixed by changing the formalparameterinthe overriding method so that it is a parameteroftypeObject.

  • 8/8/2019 Ploy Morph Ism

    27/32

    However, this allows the argument to be any type ofobject,which can produce a run-time error.

    But, we can determine ifan object isofthe correct typeusing:

    Finally, we should return false when comparing an objectto a null reference.

    A Betterequals() Method (Contd)

    ObjectinstanceofClass_Name

  • 8/8/2019 Ploy Morph Ism

    28/32

    The improved equals() method:

    A Betterequals() Method (Contd)

    public boolean equals(Object otherObject) {

    if(otherObject == null)

    return false;

    else if(!(otherObject instanceof Student))

    return false;

    else {

    Student otherStudent = (Student) otherObject; // Downcast!!

    return (this.studentNumbemer == otherStudent.studentNumber));

    }

    }

  • 8/8/2019 Ploy Morph Ism

    29/32

    BenefitsofPolymorphism

    Polymorphism enablesprogrammers to dealingeneralities and let the execution-timeenvironment handle the specifics.Programmerscan command objects to behave in mannersappropriate to those objects, without knowing thetypesofthe objects (aslong as the objects belongto the same inheritance hierarchy).

  • 8/8/2019 Ploy Morph Ism

    30/32

    Polymorphismpromotes extensibility: Softwarethat invokespolymorphic behavioris

    independent ofthe object types to whichmessages are sent.New object types that canrespond to existing method calls can beincorporated into a system without requiring

    modification ofthe base system. Only client codethat instantiates new objectsmust be modified toaccommodate new types.

    BenefitsofPolymorphism (Contd)

  • 8/8/2019 Ploy Morph Ism

    31/32

    1 // PolymorphismTest.java

    2 // Assigning superclass and subclass references to superclass and

    3 // subclass variables.

    4

    5 publicclass PolymorphismTest

    6 {

    7 publicstaticvoidmain( String args[] )

    8 {

    9 // assign superclass reference to superclass variable

    10 CommissionEmployee3 commissionEmployee = new CommissionEmployee3(

    11"Sue", "Jones", "222-22-2222", 10000, .06 );

    12

    13 // assign subclass reference to subclass variable

    14 BasePlusCommissionEmployee4 basePlusCommissionEmployee =

    15 new BasePlusCommissionEmployee4(

    16 "Bob", "Lewis", "333-33-3333", 5000, .04, 300 );

    17

    18 // invoke toString on superclass object using superclass variable

    19 System.out.printf( "%s %s:\n\n%s\n\n",

    20 "Call CommissionEmployee3's toString with superclass reference ",

    21 "to superclass object", commissionEmployee.toString() );

    22

    23 // invoke toString on subclass object using subclass variable

    24 System.out.printf( "%s %s:\n\n%s\n\n",

    25 "Call BasePlusCommissionEmployee4's toString with subclass",

    26 "reference to subclass object",

    27 basePlusCommissionEmployee.toString() );

    28

    Typical reference assignments

    Testing Polymorphism

  • 8/8/2019 Ploy Morph Ism

    32/32

    29 // invoke toString on subclass object using superclass variable

    30 CommissionEmployee3 commissionEmployee2 =31 basePlusCommissionEmployee;

    32 System.out.printf( "%s %s:\n\n%s\n",

    33 "Call BasePlusCommissionEmployee4's toString with superclass",

    34 "reference to subclass object", commissionEmployee2.toString() );

    35 } // end main

    36 } // end class PolymorphismTest

    Call CommissionEmployee3's toString with superclass reference to superclassobject:

    commission employee: Sue Jonessocial security number: 222-22-2222gross sales: 10000.00commission rate: 0.06

    Call BasePlusCommissionEmployee4's toString with subclass reference tosubclass object:

    base-salaried commission employee: Bob Lewis

    social security number: 333-33-3333gross sales: 5000.00commission rate: 0.04

    base salary: 300.00

    Call BasePlusCommissionEmployee4's toString with superclass reference tosubclass object:

    base-salaried commission employee: Bob Lewissocial security number: 333-33-3333gross sales: 5000.00commission rate: 0.04

    base salary: 300.00

    AssignareferencetoabasePlusCommissionEmployee objec

    toaCommissionEmployee3 variable

    PolymorphicallycallbasePlusCommissionEmployee s

    toString method

    Testing Polymorphism (Contd)