14
Object-oriented Object-oriented Programming in Programming in Java Java

Object-oriented Programming in Java

Embed Size (px)

DESCRIPTION

Object-oriented Programming in Java. What is OOP?. The goal is (subtype) polymorphism Achieved by Classes (user-defined types) Inheritance (is-a, substitutability) Dynamic Function Binding Function to run is bound according to the dynamic type of the object. Upcasting. - PowerPoint PPT Presentation

Citation preview

Page 1: Object-oriented Programming in Java

Object-oriented Object-oriented Programming in JavaProgramming in Java

Page 2: Object-oriented Programming in Java

What is OOP?What is OOP?

The goal is (subtype) polymorphismThe goal is (subtype) polymorphism Achieved byAchieved by

Classes (user-defined types)Classes (user-defined types) Inheritance (is-a, substitutability)Inheritance (is-a, substitutability) Dynamic Function BindingDynamic Function Binding

• Function to run is bound according to the Function to run is bound according to the dynamic dynamic typetype of the object of the object

Page 3: Object-oriented Programming in Java

UpcastingUpcasting

Storing a reference to a subtype in a Storing a reference to a subtype in a supertype variablesupertype variable

Makes sense because of the is-a Makes sense because of the is-a relationshiprelationship

Allows any subtype object to be used in a Allows any subtype object to be used in a context expecting a supertype objectcontext expecting a supertype object

Employee e = new SalariedEmployee();Employee e = new SalariedEmployee();

Page 4: Object-oriented Programming in Java

The instanceof operatorThe instanceof operator

Returns true if the left operand is the same Returns true if the left operand is the same type or a subtype of the right operandtype or a subtype of the right operand new HourlyEmployee() instanceof Employee new HourlyEmployee() instanceof Employee

is trueis true Often used before downcastingOften used before downcasting

To avoid an exceptionTo avoid an exception

Page 5: Object-oriented Programming in Java

PolymorphismPolymorphism

Dynamic variation of behaviorDynamic variation of behavior According to an object’s dynamic typeAccording to an object’s dynamic type

Calls the function corresponding to the type Calls the function corresponding to the type the reference indicates at the momentthe reference indicates at the moment

Invisibly to the programInvisibly to the program Employee e = new HourlyEmployee();Employee e = new HourlyEmployee();e.computePay();e.computePay();e = new SalariedEmployee();e = new SalariedEmployee();e.computePay(); // A different function!e.computePay(); // A different function!

Example: Figure 2Example: Figure 2

Page 6: Object-oriented Programming in Java

Benefits of OOPBenefits of OOP

High degree of separation among High degree of separation among componentscomponents Low couplingLow coupling

Insulates components from changes in Insulates components from changes in other componentsother components

Example: payroll programExample: payroll program Uses the Employee interfaceUses the Employee interface The dynamic types are invisibleThe dynamic types are invisible

Page 7: Object-oriented Programming in Java

DowncastingDowncasting

When an object must be interpreted as a When an object must be interpreted as a subtypesubtype When extracting from a collection, for When extracting from a collection, for

exampleexample Must use with careMust use with care

The object may not be the type you’re The object may not be the type you’re expectingexpecting

Checked at runtimeChecked at runtime Examples: Figures 4, 5Examples: Figures 4, 5

Page 8: Object-oriented Programming in Java

Abstract ClassesAbstract Classes

Not meant to be instantiatedNot meant to be instantiated Define an interfaceDefine an interface Also define part of the implementationAlso define part of the implementation Subclasses complete the implementationSubclasses complete the implementation abstractabstract keyword keyword

Both for classes and methodsBoth for classes and methods

Page 9: Object-oriented Programming in Java

java.lang.Objectjava.lang.Object

The Mother of all ClassesThe Mother of all Classes All objects are subtypes of ObjectAll objects are subtypes of Object

Object methods:Object methods: int hashCode( );int hashCode( ); boolean equals(Object);boolean equals(Object); String toString( );String toString( ); Among others…Among others…

Page 10: Object-oriented Programming in Java

Object.toStringObject.toString

Provides a String representation of an Provides a String representation of an objectobject

Prints the class name and the hashCodePrints the class name and the hashCode Should overrideShould override

Page 11: Object-oriented Programming in Java

Object.equals(Object)Object.equals(Object) Used for a value-based equality testUsed for a value-based equality test Override carefully:Override carefully:

Test == this firstTest == this first• if true, return trueif true, return true

Test instanceof TheClassTest instanceof TheClass• if false, return falseif false, return false

Then check all the fieldsThen check all the fields• Use equals() recursively for object fieldsUse equals() recursively for object fields• Can super.equals() for inherited fieldsCan super.equals() for inherited fields

Examples: ColorPoint (next slide) and Examples: ColorPoint (next slide) and SuperEquals.javaSuperEquals.java

Always override hashCode() if you override Always override hashCode() if you override equals()equals()

Page 12: Object-oriented Programming in Java

ColorPointColorPoint

public boolean equals(Object other) { if (this == other) return true; else if (!(other instanceof ColorPoint)) return false; ColorPoint p = (ColorPoint) other; return (super.equals(p) && p.color.equals(this.color));}

int x, y Color color

Instance variables in parent class, Point:

Instance variable in child class, ColorPoint:

Page 13: Object-oriented Programming in Java

Floating-point FieldsFloating-point Fields

Don’t compare for equality with ==!Don’t compare for equality with ==! Has to do with special values (NaN, etc.)Has to do with special values (NaN, etc.)

Convert floats to int with Convert floats to int with Float.floatToIntBitsFloat.floatToIntBits

Convert doubles to long with Convert doubles to long with Double.doubleToLongBitsDouble.doubleToLongBits

Compare the resulting integers with ==Compare the resulting integers with ==

Page 14: Object-oriented Programming in Java

hashCodehashCode Used to associate an object with an intUsed to associate an object with an int Used in hash tables and other containersUsed in hash tables and other containers Should be “as unique as possible”Should be “as unique as possible” Rules:Rules:

Boolean: (f ? 0 : 1)Boolean: (f ? 0 : 1) byte, char, or short: (int) fbyte, char, or short: (int) f Long: (int)(f ^ (f>>>32))Long: (int)(f ^ (f>>>32)) Float: Float.floatToIntBits(f)Float: Float.floatToIntBits(f) Double: Double.doubleToLongBits(f)Double: Double.doubleToLongBits(f) Combine with prime numbers: h = 37*f1; h = 37*h;…Combine with prime numbers: h = 37*f1; h = 37*h;… Objects: combine their hashcodes Objects: combine their hashcodes (see pp. 197-198)(see pp. 197-198)