<<

Object Oriented Programming Designing and Object Oriented Programming is not new. – Simula 1 (1962 - 1965) and Simula 67 (1967) Norwegian Implementing Classes Computing Center, Oslo, Norway by Ole-Johan Dahl and Kristen Nygaard. Topic 6 – Smalltalk (1970s), Alan Kay's group at Xerox PARC – ++ (early 1980s), Bjarne Stroustrup, Bell Labs Don't know much geography – Eiffel, Bertrand Meyer Don't know much trigonometry – Java and others Don't know much about algebra Becoming the dominant style for implementing Don't know what a slide rule is for complex programs with large numbers of -Sam Cooke interacting components and in education

AP Computer Science Designing and Implementing Classes 1 AP Computer Science Designing and Implementing Classes 2

Tenants of Object Oriented Main Tenets of OO Programming Programming - Encapsulation Encapsulation information hiding, using something without – abstraction, information hiding, responsibility knowing (or caring or having to worry) about driven programming how it works. abstraction Inheritance achieved via classes and objects. Useful in – code reuse, specialization breaking up large problems based on a study Polymorphism of the data involved first – allows old code to use new code, do X, where X Don Knuth, Turing award winner is different depending on the type of object algorithms + data structures = programming

AP Computer Science Designing and Implementing Classes 3 AP Computer Science Designing and Implementing Classes 4 Class and Objects Using Objects What are classes? An object is a model (abstraction of) a real- – classes are user defined data types. (as opposed to the primitive data types) world object. – classes specify the operations that may be carried out on – it is a collection of variables (fields) and methods variables of this type. Behaviors A method is an operation on an object. – They also specify what sub data the variable consists of and have the implementation of the behaviors listed Objects interact with messages. A message above. is sent to an object and specifies the method – objects are simply variables of a given class that object should perform. It is easier to describe how to use an object than it – The sender (normally another object) doesn't is to create a class know anything about how the method is – easier to teach some one to drive car or teach someone performed how to design and build a car? AP Computer Science Designing and Implementing Classes 5 AP Computer Science Designing and Implementing Classes 6

Using Objects The dot Operator Objects are variables, they have a declared type Once an object is created the dot operator and a set of behaviors or operations ( . ) is used to perform operations on the object or access sub data in the object String name1 = new String("Olivia A. Scott"); String name2 = new String("Isabelle M. Scott"); String name1 = new String("Olivia A. Scott"); char first = name1.charAt(0); All object variables are reference variables (i.e. char second = name2.charAt(1); pointers) Any public part of the object may be accessed. Objects must be dynamically allocated using the normally only methods are public. new operator and calling a constructor – Must call a method that actually exists and match one of – special cases for Strings and arrays the parameter signatures or syntax error To determine the various behaviors of an object the dot operator calls or invokes the method must look at the class documentation flow of control shifts to that code

AP Computer Science Designing and Implementing Classes 7 AP Computer Science Designing and Implementing Classes 8 Object Data Object Methods occasionally fields of an object are public, but this Object methods either is generally considered bad style – tell you something about the object array length vs. String length • accessors, have a return value int[] list = new int[x]; • the charAt and length methods in String for(int i = 0; i < list.length; i++) – change the object in some way Only a good idea if the data is constant. • mutators, no return value. Changes the state of the Good object oriented programming style calls for object any changes to an object to be done via a method • the setSize method in Rectangle call – do both, some people consider this bad style Normally a data's object is hidden (encapsulated) • mutators that return a value, return value and a and if I am using an object I don't know or care change to the object's state about the details of that implementation AP Computer Science Designing and Implementing Classes 9 AP Computer Science Designing and Implementing Classes 10

Finding Object Methods Classes fundamental unit of OO programming JavaTM 2 Platform, Standard Edition, v 1.4.x API Specification Java programs of any significance are a – Your best friend in the world collection of classes http://java.sun.com/j2se/1.4.1/docs/api/ Has specification for all classes in the Java standard library This is a rather smallish Only documents the public portion, what we program and it contains can use! 6 classes not counting another 6 classes from A product of javadoc the Java Standard Library java source code in -> easy to read html out AP Computer Science Designing and Implementing Classes 11 AP Computer Science Designing and Implementing Classes 12 What are Classes? More on Classes classes are blueprints Each class in Java is contained in its own file with the name – they specify what new objects will contain and what matching the class name and with the .java extension can be done to the objects The basics elements of a class are – classes are analogous to data types and objects are – constructors • used in the creation of objects. Similar to methods (procedures and the variables of that type functions). classes consist of an interface (what is it?) and • Normally several overloaded for the convenience of the class users an implementation (how it is done?) – methods • instance methods and class () methods – interface describes the ways an object of this type may – variables (or fields) be created via constructors and how a client may use • instance variables and class variables (static) or manipulate an object of this type via methods – constants – implementation is hidden and of no concern to the • instance (rare) and class (static) client. implementation can be changed without affecting any client code AP Computer Science Designing and Implementing Classes 13 AP Computer Science Designing and Implementing Classes 14

The Die Class The Die Class Interface Consider a class used Constructors (used in creation of objects) to model a die – default, single int parameter to specify the What is the interface? What number of sides, int and boolean to determine if actions should a die be able should roll to perform? Mutators (change state of objects) –roll Accessors (do not change state of objects) – getTopSide, getNumSides, toString The methods or behaviors can be broken up Public constants into constructors, mutators, accessors – DEFAULT_SIDES

AP Computer Science Designing and Implementing Classes 15 AP Computer Science Designing and Implementing Classes 16 Visibility Modifiers The Die Class Implementation All parts of a class have visibility modifiers Implementation is made up of constructor code, method code, and private data members of the – Java keywords class. – public, protected, private, (no modifier means package access) scope of data members / instance variables – private data members may be used in any of the – do not use these modifiers on local variables (syntax error) constructors or methods of a class public means that constructor, method, or field may Implementation is hidden from users of a class and be accessed outside of the class. can be changed without changing the interface or – part of the interface affecting clients (other classes that use this class) – constructors and methods are generally public – Example: Previous version of Die class, private means that part of the class is hidden and DieVersion1.java Once Die class completed can be used in anything inaccessible by code outside of the class requiring a Die or situation requiring random – part of the implementation numbers between 1 and N – data fields are generally private – DieTester class. What does it do? AP Computer Science Designing and Implementing Classes 17 AP Computer Science Designing and Implementing Classes 18

DieTester method DieTester continued

int total = 0; int numRolls = 0; public static void main(String[] args) { do final int NUM_ROLLS = 50; { d1.roll(); final int TEN_SIDED = 10; d2.roll(); Die d1 = new Die(); d3.roll(); Die d2 = new Die(); total = d1.getTopSide() + d2.getTopSide () Die d3 = new Die(TEN_SIDED); + d3.getTopSide (); final int MAX_ROLL = d1.getNumSides() + numRolls++; d2.getNumSides() + d3.getNumSides(); } while(total != MAX_ROLL);

for(int i = 0; i < NUM_ROLLS; i++) System.out.println("\n\nNumber of rolls to get " { d1.roll(); + MAX_ROLL + " was " + numRolls); d2.roll(); System.out.println("d1: " + d1.getResult() + " d2: " + d2.getTopSide() + " Total: " + (d1.getTopSide() + d2.getTopSide() ) ); }

AP Computer Science Designing and Implementing Classes 19 AP Computer Science Designing and Implementing Classes 20 The Steps of Class Design Correctness Sidetrack Requirements When creating the public interface of a class give – what is the problem to be solved careful thought and consideration to the contract – detailed requirements lead to specifications you are creating between yourself and users (other Nouns may be classes programmers) of your class Use preconditions to state what you assume to be Verbs signal behavior and thus methods (also true before a method is called defines a classes responsibilities) – caller of the method is responsible for making sure these walkthrough scenarios to find nouns and verbs are true implementing and testing of classes Use postconditions to state what you guarantee to be true after the method is done if the preconditions design rather than implementation is normally the are met hardest part – implementer of the method is responsible for making – planning for reuse sure these are true

AP Computer Science Designing and Implementing Classes 21 AP Computer Science Designing and Implementing Classes 22

Precondition and Object Behavior - Instantiation Postcondition Example Consider the DieTester class Die d1 = new Die(); /* pre: sides > 1 Die d2 = new Die(); post: getTopSide() = 1, getNumSides() = sides Die d3 = new Die(10); */ When the new operator is invoked control is public Die(int numSides) transferred to the Die class and the specified { if(numSides <= 1) constructor is executed, based on parameter matching throw new IllegalArgumentException("numSides is " + numSides + ". numSides must be > 1"); Space(memory) is set aside for the new object's fields iMyNumSides = numSides; The memory address of the new object is passed iMyResult = 1; back and stored in the object variable (pointer) assert getTopSide() == 1 && getNumSides() == numSides; After creating the object, methods may be called on it. } AP Computer Science Designing and Implementing Classes 23 AP Computer Science Designing and Implementing Classes 24 Creating Dice Objects Objects memory a Die object Every Die object created has its own address instance of the variables declared in the 6 1 d1 class blueprint DieTester class. Sees iMySides iMyResult Die class. private int iMySides; interface of Die class Sees a Die object private int iMyResult; implementation. memory (of Die class.) thus the term 6 1 address the instance vars are part of the hidden d2 iMySides iMyResult implementation and may be of any a Die object – unless they are public, which is almost always a memory bad idea if you follow the tenets of information address 10 1 hiding and encapsulation d3 iMySides iMyResult AP Computer Science Designing and Implementing Classes 25 AP Computer Science Designing and Implementing Classes 26

Complex Objects The Implicit Parameter What if one of the instance variables is itself Consider this code from the Die class an object? public void roll() add to the Die class { iMyResult = ourRandomNumGen.nextInt(iMySides) + 1; private String myName; } Taken in isolation this code is rather confusing. memory a Die object what is this iMyResult thing? address 6 1 memory address – It's not a parameter or local variable d1 iMySides iMyResult myName – why does it exist? d1 can hold the memory address – it belongs to the Die object that called this method of a Die object. The instance variable a String object – if there are numerous Die objects in existence myName inside a Die object can hold implementation – Which one is used depends on which object called the memory address of a String object details not shown the method.

AP Computer Science Designing and Implementing Classes 27 AP Computer Science Designing and Implementing Classes 28 The this Keyword this Visually memory // in some class other than Die address When a method is called it may be necessary Die d3 = new Die(); for the calling object to be able to refer to itself d3.roll(); d3 – most likely so it can pass itself somewhere as a // in the Die class parameter public void roll() when an object calls a method an implicit { iMyResult = ourRandomNumGen.nextInt(iMySides) + 1; reference is assigned to the calling object /* OR the name of this implicit reference is this this.iMyResult… a Die object this is a reference to the current calling object */ } memory and may be used as an object variable (may not address 6 1 declare it) this iMySides iMyResult

AP Computer Science Designing and Implementing Classes 29 AP Computer Science Designing and Implementing Classes 30

A Possible Equals Method An equals method public boolean equals(Object otherObject) { Die other = (Die)otherObject; return iMySides == other.iMySides working with objects of the same type in a && iMyResult== other.iMyResult class can be confusing && myName.equals( other.myName ); } write an equals method for the Die class. Declared Type of Parameter is Object not Die assume every Die has a myName instance override (replace) the equals method instead of variable as well as iMyNumber and iMySides overload (present an alternate version) – easier to create generic code we will see the equals method is inherited from the Object class access to another object's private instance variables? AP Computer Science Designing and Implementing Classes 31 AP Computer Science Designing and Implementing Classes 32 Another equals Methods A "Perfect" Equals Method From Cay Horstmann's Core Java public boolean equals(Object otherObject) { Die other = (Die)otherObject; public boolean equals(Object otherObject) { // check if objects identical return this.iMySides == other.iMySides if( this == otherObject) && this.iMyNumber == other.iMyNumber return true; && this.myName.equals( other.myName ); // must return false if explicit parameter null } if(otherObject == null) return false; // if objects not of same type they cannot be equal Using the this keyword / reference to access the implicit parameters if(getClass() != otherObject.getClass() ) return false; instance variables is unnecessary. // we know otherObject is a non null Die If a method within the same class is called within a method, the Die other = (Die)otherObject; original calling object is still the calling object return iMySides == other.iMySides && iMyNumber == other.iMyNumber && myName.equals( other.myName ); } AP Computer Science Designing and Implementing Classes 33 AP Computer Science Designing and Implementing Classes 34

the instanceof Operator Class Variables and Class Methods instanceof is a Java keyword. Sometimes every object of a class does not part of a boolean statement need its own copy of a variable or constant public boolean equals(Object otherObj) The keyword static is used to specify { if otherObj instanceof Die class variables, constants, and methods { //now go and cast private static Random ourRandNumGen // rest of equals method = new Random(); } public static final int DEFAULT_SIDES = 6; } The most prevalent use of static is for class Should not use instanceof in equals methods. constants. instanceof has its uses but not in equals – if the value can't be changed why should every object have a copy of this non changing value because of the contract of the equals method AP Computer Science Designing and Implementing Classes 35 AP Computer Science Designing and Implementing Classes 36 Syntax for Accessing Class Variables Class Variables and Constants public class UseDieStatic { public static void main(String[] args) the Die class { System.out.println( "Die.DEFAULT_SIDES " + Die.DEFAULT_SIDES ); memory // Any attempt to access Die.ourRandNumGen 6 address // would generate a syntax error DEFAULT_SIDES ourRandNumGen Die d1 = new Die(10);

a Random object System.out.println( "Die.DEFAULT_SIDES " All objects of type Die have + Die.DEFAULT_SIDES ); access to the class variables implementation System.out.println( "d1.DEFAULT_SIDES " and constants. details not shown + d1.DEFAULT_SIDES ); // regardless of the number of Die objects in A public class variable or constant // existence, there is only one copy of DEFAULT_SIDES may be referred to via the class name. // in the Die class } // end of main method } // end of UseDieStatic class AP Computer Science Designing and Implementing Classes 37 AP Computer Science Designing and Implementing Classes 38

Static Methods Static Methods Continued static has a somewhat different Since there is no implicit object parameter meaning when used in a method sent to the static method it does not have declaration access to a copy of any objects instance static methods may not manipulate any variables instance variables – unless of course that object is sent as an in non static methods, some object explicit parameter invokes the method Static methods are normally utility methods d3.roll(); or used to manipulate static variables ( class variables ) the object that makes the method call is an implicit parameter to the method The Math and System classes are nothing but static methods

AP Computer Science Designing and Implementing Classes 39 AP Computer Science Designing and Implementing Classes 40 static and this Why does this work (added to Die class) public class Die { public void outputSelf() { System.out.println( this ); } }

but this doesn't? public class StaticThis { public static void main(String[] args) { System.out.println( this ); } }

AP Computer Science Designing and Implementing Classes 41