Quick viewing(Text Mode)

Polymorphism and Casting Dynamic Binding and Arguments

Polymorphism and Casting Dynamic Binding and Arguments

II 4003-232-07 (Winter 20072) Polymorphism and Casting

Week 2: Inheritance, Polymorphism, and (text 9.7 – 9.8) Interfaces

Richard Zanibbi Rochester Institute of Technology

Dynamic Binding Dynamic Binding and Arguments (or Polymorphism of Methods) Method Arguments in Java Definition – May be of any type that is considered a subtype (e.g. subclass) of – Selecting the definition of a method to invoke at runtime (i.e. which the parameter type. definition to bind to the method call) – e.g. public static void m(Object x) from the previous example will – Must match method name, number, order and types of arguments accept any object belonging to a subclass of Object as an – Important when methods can be overridden (e.g. toString()) argument (i.e. from any class!) – e.g. public static void p(double x) may accept any of the numeric types for x (, short, int, long, float, double) and implicitly Dynamic Binding In Java perform a widening type conversion (cast) if necessary: see p.40 in The search for which definition to bind to a method call starts from the course text. actual (constructed) class of an object, or a named class, and – For overloaded methods, start with actual operands’ type and use proceeds up the inheritance hierarchy towards Object. the method definition with the most specific (‘lowest’) accepting formal parameter Example – Example: OverloadedNumbers.java PolymorphismDemo.java (Liang pp. 311-312) GraduateStudent Student Person Object – Takes advantage of dynamic binding, ability to handle many types in the same way (generically) and invoke overridden methods - 3 - - 4 -

The ‘instanceof’ operator Type Casting Objects Upcasting Use – Converting the type of an object to a superclass (“up” the inheritance/type hierarchy). Usually not explicit, as properties of A boolean operator that tests whether an object superclasses are inherited by subclasses automatically. belongs to a given class. – e.g. Object o = new Student(); // Student referenced as an Object – Similarly, parameters of type Object may accept objects of any other type, with an implicit cast to class Object.

Examples Downcasting Circle myCircle = new Circle(1.0); – Converting the type of an object to a subclass (“down” the inheritance hierarchy). Requires explicit casting, with a check to – myCircle instanceof Circle // true ensure that the cast will be successful using instanceof. – e.g. if (o instanceof Student) Student s = (Student) o; – myCircle instanceof Object // true – e.g. TestPolymorphismCasting.java (Liang p. 315) – myCircle instanceof String // false Why do we need to check types before downcasting?

- 5 - - 6 -

1 Subtle Point: Matching the Method vs. Precedence of Cast vs. Dot operator Selecting the Method Definition Caution! Matching the Method Signature (static) – For objects, the selection of which method signature to use is The access (dot) operator has higher precedence determined at compile time based on the type of a reference. than type casting. – Put another way, the type of a reference to an object determines which class is active for an object – If the active class interface is a superclass of the class that defines Fix: a desired method, it will not be found. • e.g. Object o = new Circle(1); o.getRadius() // won’t work. Put results casting operations in brackets when • Object o = new Circle(1); ((Circle)o).getRadius() // will work. paired with access operators, e.g. ((Circle)object).getArea() vs. Selecting the Method Definition (dynamic) Is done dynamically at runtime (dynamic binding). The actual (Circle)object.getArea() (constructed) class determines the implementation used.

- 7 - - 8 -

void finalize() Methods in the Object Class – Invoked by the garbage collector before an object is destroyed. boolean equals(Object o) – Objects without a reference are “garbage.” – By default, does nothing. Test if another object is the same as the current one (test by reference value) – You should never invoke finalize() in a program! – Example: FinalizationDemo.java (p. 323) int hashCode() Used to define integer hash codes for hash sets (a type of Class getClass() structure). In Object, this is the object’s address. – The JVM creates objects to represent classes (“meta- objects”), including the class name, constructors, and methods. There is a class “Class” used to define these. Object clone() – It is possible to query a Class object to get information Copies the state of an object to produce a copy. about a class at runtime. e.g. int[] targetArray = (int []) sourceArray.clone(); – Every object may be asked to return the Class object (meta-object) with which it is associated using getClass()

- 9 - - 10 -

getClass() example Hiding Data and Methods

Object obj = new Object(); • Static Methods • Static/Instance Data Members Class = obj.getClass(); cannot be overridden; only hidden. (Avoid this!) System.out.println(“Class is: “ + metaObject.getName()); Accessing Hidden Methods and Data – Using super() in the subclass – Using a reference variable of the superclass type (i.e. use the superclass type (interface)) produces – Unlike instance methods, static methods and data members are bound at compile time (“statically”) – Example: HidingDemo.java (p. 326) – ** Static methods and fields can always be accessed directly using Class is: java.lang.Object the class name (if it is visible, using Class.staticMethod() )

- 11 - - 12 -

2 B. Indicate whether each of the following statements are valid or Exercise: Polymorphism invalid. 1. Object o1 = new String(“test”); 2. if (o1 instanceof String) { }; A. What is wrong with the following code? 3. if (o1 instanceof Circle) { }; 4. Object o2 = new Circle(1); // passed radius 5. String s1 = o1; public class Test { 6. String s2 = (String) o1; public static void main(String[] args) { 7. Object o3 = (Object) s2; Object fruit = new Fruit(); 8. String s4 = ((Object)o1).toString(); Object apple = (Apple) fruit; 9. String s5 = (Circle)o2.toString(); 10. Object o4 = (Object) o1; } } . Why should instanceof be used before performing a downcast of an Object? class Apple extends Fruit { } class Fruit { }

- 13 - - 14 -

Abstract Method

Definition A method which has a signature, but no body. All abstract methods are instance methods (non-static). Abstract Classes and Interfaces • e.g. public abstract int deviseNumber(); Purpose – Class design: permits defining a method signature whose definition may be provided in subclasses. – Through dynamic binding and overriding, this will allow different versions of the method to be invoked at run time for objects that belong to the abstract class, but different actual subclasses (example later).

- 16 -

Abstract Class Concrete Class A class which may be used to create instances . Definition Abstract classes are not concrete classes. – A class which may not have any instances created from it, used solely to define subclasses of itself. Otherwise, it is a normal class, and is included in the class inheritance hierarchy. Additional Notes on Abstract Classes – All classes that contain abstract methods *must* be declared – May still have constructors defined (though protected abstract. access more appropriate than public) – e.g. public abstract class GeometricObject() { } – May be used as a for reference vars. • e.g. GeometricObject g = new Circle(1.0); Class Design • This is one of their key uses; as an interface to access common – In general, superclasses should be designed to contain common data and methods of different subclasses. features of subclasses (to maximize code reuse, e.g. Object class) – Abstract classes are useful for defining and using common data and behaviours for subclasses that may represent significantly different Subclasses of Abstract Classes object types. – Must implement all abstract methods, or also be – Defines an interface for these (possibly very) different subclasses declared abstract (no instances).

- 17 - - 18 -

3 (abstract class)

(abstract methods)

- 19 - - 20 -

A Yet More Restricted Class Type: Examples Interfaces in Java TestGeometricObject.java (p. 345) Definition – A type of class which defines only (public static final) constants and (public) abstract instance methods. Uses of Abstract Class: – Provides a data type for reference variables from which – Abstract class allows us to get areas and perimeters the interface may be used to act on objects associated using a single interface, though the computation of with the interface type. these in the Circle and Rectangle classes are completely different. – NOTE: Interfaces are not part of the class hierarchy

Another Example (Text 10.3) Java Syntax Calendar class (abstract) and Gregorian Calendar Defined using the “interface” rather than “class” keyword (concrete subclass of Calendar) • e.g. public interface Cloneable { ... }

- 21 - - 22 -

Motivation for Interfaces in Java Example: Comparable Interface Purpose Multiple Inheritance is Prohibited – Allow definition of a method for determining which of a We cannot inherit from multiple classes; in particular, pair of objects of the same class is ‘larger’ or if they are state is only inherited through a strict linear path in the the ‘same size.’ inheritance tree (hierarchy) – Can then use compareTo() to compare Strings, Students (e.g. by student id), Geometric objects (e.g. by But... area), etc. using a single method with different definitions (one per class) – Still wish to allow very different data types (classes) to Returns: have common methods to support generic programming -1: this < argument package java.lang (e.g. the ability to compare objects using a single 0: this, argument same interface (Comparable)) public interface Comparable { 1: this > argument – A class may ‘implement’ one or more interfaces to public abstract int compareTo(Object o); support these ‘generic’ types of computation. }

- 23 - - 24 -

4 Example Classes Example of a ‘Generic’ Comparison Using Comparable Interface Function public class String extends Object implements Comparable { ... } public class Max { public static Comparable max(Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) public class Date extends Object implements Comparable { return o1; else ... } return o2 } } Interface as a Reference Variable Type The following are valid for String object s and Date object d: Example Usage: String s1 = “a”; String s2 = “b”; • s instanceof String, String s3 = (String)Max.max(s1,s2); • s instanceof Object, • s instanceof Comparable Date d1 = new Date(); Date d2 = new Date(); • d instanceof java.util.Date, Date d3= (Date)Max.max(d1,d2); • d instanceof Object, • d instanceof Comparable Any class that implements Comparable can be used with Max.max()

- 25 - (e.g. a revised Rectangle class (see p. 350)) - 26 -

UML Representation of Interfaces and Inheritance Inheritance/Implementation Classes Implementing Interfaces – Concrete and Abstract classes may inherit from only one parent. – However, they may implement multiple interfaces. public class A extends B implements InterfaceA, InterfaceB, ..., InterfaceN { }

Interfaces extending Interfaces Interfaces may inherit from and extend one or more interfaces. public Interface NewInterface extends IntA, ...., IntN { }; Objects of Class2 are instances of all the other classes and interfaces - 27 - shown. This means variables referring to a Class2 object may be - 28 - any of these types.

Marker Interfaces

Marker Interface – An interface that contains no constants or methods; ‘flags’ a class as having certain properties (e.g. to tell Java to permit certain operations) – e.g. “Cloneable” (designates that objects of a class may have their state copied into another object)

public class House implements Cloneable, Comparable { ... }

House h1 = new House(1,1750.50); // id, area House h2 = (House)house1.clone();

.. See text Section 10.4.4 for details.

**Shallow vs. Deep Copies – Shallow: object references copied by value (copies reference to a single object) - danger of manipulating the “original” data in this case – Deep: object data is copied into new objects, and “copied” references point to the new objects and not the original ones (e.g. using clone())

- 29 -

5