CSC 245 Chapter 2, Spring 2015

Lebanese American University · Objects and Data Abstraction · 14 pages

All CSC 245 files
CSC 245 Chapter 2, Spring 2015, page 1

Stuck on a question? A tutor can walk you through it.

CSC 245 Chapter 2, Spring 2015, page 2 CSC 245 Chapter 2, Spring 2015, page 3 CSC 245 Chapter 2, Spring 2015, page 4 CSC 245 Chapter 2, Spring 2015, page 5 CSC 245 Chapter 2, Spring 2015, page 6 CSC 245 Chapter 2, Spring 2015, page 7 CSC 245 Chapter 2, Spring 2015, page 8 CSC 245 Chapter 2, Spring 2015, page 9 CSC 245 Chapter 2, Spring 2015, page 10

Showing the first 10 of 14 pages. Download the PDF to see all of it.

More CSC 245 files

Show the text of this chapter
Objects and Data Abstraction (v1.05) 1 CSC 245: Objects and Data Abstraction Chapter 2 Abstract Data Types & Java Classes Objects and Data Abstraction (v1.05) 2 Outline � Classes & Members � Defining a New Class & its Members � Constructors � Accessor Methods � Using a Class � Creating & Using Objects � Object References � Packages � Parameters, Equals Methods, Clones Objects and Data Abstraction (v1.05) 3 Objects � Object Oriented Programming (OOP) � An approach in which data occurs in tidy packages called Objects. � Objects are manipulated using functions called methods which are part of their objects � Class � Definition or template for objects (called instances) � Data members of an object. � Methods of an object. Objects and Data Abstraction (v1.05) 4 Abstract Data Types � Information Hiding � An example of the separation of specification from implementation � Abstract Data Type (ADT) � Specification of a class’s interface. � Class is an implementation of an ADT � We will present throughout this chapter two examples of ADTs Objects and Data Abstraction (v1.05) 5 Class Members � A class is a new kind of data type � A class includes � Data � Integers, characters, floats, etc. � Methods � Operations on objects. � Constructors � Initialize data of newly created objects. � View class as an ADT � Can specify which members are visible to the outside. � Taken all together, the above elements constitute the class members Objects and Data Abstraction (v1.05) 6 Example: Mechanical Throttle � Description � A class that is used to store and manipulate the status of mechanical throttle � A throttle is a lever that can be moved to control fuel flow. � Similar to a gas pedal. � Throttle Positions � Shutoff position � Allows no fuel flow. � On positions � Flow proportional to lever location. � Topmost position—maximum flow. � Initialization � Number of positions � Throttle @ shutoff position. Objects and Data Abstraction (v1.05) 7 Example: Mechanical Throttle… � Constructor � Creates new throttle with: � One shutoff position & � A specified number of on positions. � Methods � What is fuel flow? � Proportion of maximum flow. � Is throttle on? � Return true/false based on state of throttle. � Shift throttle by a given amount. � Move throttle back to shutoff position. Objects and Data Abstraction (v1.05) 8 Example: Mechanical Throttle… � Defining New Class public class Throttle { private int top; // topmost position of lever private int position; // current position of lever } � Class header � Instance variables // Implementations of constructors & methods // go here Objects and Data Abstraction (v1.05) 9 Constructors � Instance variables initialized to Java’s default values. � 0 for numbers, false for booleans, etc. � Declaration w/initialization overrides default values. int step = 10; � Constructor’s name must be class’s name. � A constructor does not have a return value. Objects and Data Abstraction (v1.05) 10 Example: Throttle Example… � Constructor—Specification public Throttle(int size) Construct a Throttle with a specified number of positions. � Parameters size—number of on positions for this new Throttle. � Precondition size > 0 � Postcondition This Throttle has been initialized with the specified number of on positions above the shutoff position, and is currently shut off. � Throws: IllegalArgumentException Indicates that size is not positive. Objects and Data Abstraction (v1.05) 11 Example: Mechanical Throttle… � Constructor—Implementation public Throttle(int size) { if (size <= 0) throw new IllegalArgumentException("Size <= 0: " + size); top = size; // No assignment needed for position. // default value is zero. } Objects and Data Abstraction (v1.05) 12 No-Arguments Constructor � Does not need information to initialize data members. � Automatically created by Java. � When no other constructors defined! � Can be overridden by implementer. Objects and Data Abstraction (v1.05) 13 Methods � Accessor � Gives info about object without altering it. � Also called get-methods or getters. � Modifier � May change object's state. � Methods implement operations on objects. � Inspect & modify object's data members. Objects and Data Abstraction (v1.05) 14 Example: Mechanical Throttle… � Accessor Method—getFlow public double getFlow() Get the current flow of this Throttle. � Returns the current flow rate (always in the range [0.0 … 1.0]) as a proportion of the maximum flow. public double getFlow() { return (double) position / (double) top; } Objects and Data Abstraction (v1.05) 15 Example: Mechanical Throttle… � Accessor Method—isOn public boolean isOn() Check whether this Throttle is on. � Returns true if this Throttle's flow is above zero. Otherwise, return false. public boolean isOn() { return (getFlow() > 0); // Equivalent to (position > 0) } Objects and Data Abstraction (v1.05) 16 Example: Mechanical Throttle… � Modification Method—shutOff public void shutOff() Turn off this Throttle. Postcondition: This Throttle's flow has been shut off. public void shutOff() { position = 0; } Objects and Data Abstraction (v1.05) 17 Example: Mechanical Throttle… � Modification Method—shift public void shift(int amount) Move this Throttle's position up or down. � Parameters amount—amount to move position up or down (+ve for up, -ve for down) � Postcondition This Throttle's position has been moved by specified amount. Position always between zero & top position. Objects and Data Abstraction (v1.05) 18 Example: Mechanical Throttle… � Modification Method—shift… public void shift(int amount) { if (amount > top – position) // Adding amount puts position above top. position = top; else if (position + amount < 0) // Adding amount puts position below zero. position = 0; else // Adding amount puts position in range [0…top] position += amount; } Objects and Data Abstraction (v1.05) 19 Using a Class � Creating Objects Throttle control; � control refers to an instance of class Throttle. � Initialized to null. � Cannot invoke any method on control yet. new Throttle(100); � Create a new Throttle object. � Instance variable top initialized to 100. Objects and Data Abstraction (v1.05) 20 Using a Class � Creating Objects… � Throttle control = new Throttle(100); � Throttle control; control = new Throttle(100); � Equivalent sets of statements � control refers to instance of Throttle. Objects and Data Abstraction (v1.05) 21 Using a Class… � Using Objects � control.shift(3); � control.isOn(); � Invoke methods shift and isOn on object that control refers to. � Method Call Components � Object reference (e.g., control). � Field selector operator (.) � Method name (e.g., shift) � Parameter list � May be empty. Objects and Data Abstraction (v1.05) 22 Using a Class… � Example final int SIZE = 8; // Size of the Throttle. final int SPOT = 3; // Target of Throttle's lever. Throttle small = new Throttle(SIZE); small.shift(SPOT); System.out.print ("My small throttle is now at position"); System.out.println(SPOT + " out of " + SIZE + "."); System.out.println("The flow is now: " + small.getFlow()); My small throttle is now at position 3 out of 8. The flow is now: 0.375. Objects and Data Abstraction (v1.05) 23 Using a Class… � Example—Multiple Instances of Same Class Throttle tiny = new Throttle(4); Throttle huge = new Throttle(10000); tiny.shift(2); huge.shift(2500); � Objects tiny & huge are instances of the class Throttle. � Same methods. � Different copies of instance variables. Objects and Data Abstraction (v1.05) 24 Reference Variable Assignment � Code Example 1 Throttle t1; Throttle t2; t1 = new Throttle(100); t1.shift(25); t2 = t1; t2.shift(-5); � Aliases � Refer to the same object. Throttle t1 Throttle t2 top 100 position ??? Objects and Data Abstraction (v1.05) 25 Reference Variable Assignment… � Code Example 2 Throttle t1; Throttle t2; t1 = new Throttle(100); t1.shift(25); t2 = new Throttle(100); t2.shift(25); � true Expressions � t1 != t2 � t1.equals(t2) Throttle t1 Throttle t2 top 100 position 25 top 100 position 25 Objects and Data Abstraction (v1.05) 26 Equality Test � (t1 == t2) is true Throttle t1; Throttle t2; t1 = new Throttle(100); t1.shift(25); t2 = t1; � Variables refer to SAME object. Throttle t1 Throttle t2 top 100 position 25 Objects and Data Abstraction (v1.05) 27 Equality Test… � (t1 == t2) is false Throttle t1; Throttle t2; t1 = new Throttle(100); t1.shift(25); t2 = new Throttle(100); t2.shift(25); � Variables do NOT refer to SAME object. Throttle t1 Throttle t2 top 100 position 25 top 100 position 25 Objects and Data Abstraction (v1.05) 28 Class Location—Specification � Constructor public Location(double xInitial, double yInitial) � Constructs a Location with specified coordinates. � Parameters xInitial—the initial x coordinate of this Location. yInitial—the initial y coordinate of this Location. � Postcondition This Location has been initialized at the given coordinates. � clone Method public Object clone() � Generate a copy of this Location. � Returns A copy of this Location. Changes to copy do not affect this Location. Objects and Data Abstraction (v1.05) 29 Class Location—Specification… � distance Method public static double distance (Location p1, Location p2) � Compute the distance between two Locations. � Parameters p1—the first Location. p2—the second Location. � Returns the distance between p1 and p2. � Note The answer is Double.POSITIVE_INFINITY if the distance calculations overflows. The answer is Double.NaN if either Location is null. Objects and Data Abstraction (v1.05) 30 Class Location—Specification… � equals Method public boolean equals(Object obj) � Compare this Location with another object. � Parameters obj—an object with which this Location is compared. � Returns true if obj refers to a Location with same value. Otherwise, false. � Note The answer is false if obj is null or is not a Location. Objects and Data Abstraction (v1.05) 31 Class Location—Specification… � midPoint Method public static Location midPoint (Location p1, Location p2) � Generates & returns a Location halfway between two others. � Parameters p1—the first Location. p2—the second Location. � Returns a Location that is halfway between p1 and p2. � Note The answer is null if p1 or p2 is null. Objects and Data Abstraction (v1.05) 32 Class Location—Specification… � getX & getY Methods public double getX() -and- public double getY() � Get the x or y coordinate of this Location. � Returns the x or y coordinate of this Location. � rotate90 Method public void rotate90() � Rotate this Location 90o in a clockwise direction. � Postcondition This Location has been rotated clockwise 90o around the origin. Objects and Data Abstraction (v1.05) 33 Class Location—Specification… � shift Method public void shift(double xAmount, double yAmount) � Move this Location by given amounts along x & y axes. � Postcondition This Location has been moved by given amounts along the two axes. � Note shift may cause a coordinate to go above Double.MAX_VALUE or below – Double.MAX_VALUE. Subsequent calls to accessor return Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY. � toString Method public String toString() � Generate a string representation of this Location. � Returns � a string representation of this Location. Objects and Data Abstraction (v1.05) 34 Location Class Objects and Data Abstraction (v1.05) 35 Objects and Data Abstraction (v1.05) 36 Objects and Data Abstraction (v1.05) 37 Objects and Data Abstraction (v1.05) 38 Objects and Data Abstraction (v1.05) 39 Objects and Data Abstraction (v1.05) 40 Objects and Data Abstraction (v1.05) 41 Objects and Data Abstraction (v1.05) 42 Objects and Data Abstraction (v1.05) 43 Objects as Parameters � Parameters � Formal—names of parameters as defined in method header. � Actual—names of parameters in method invocation. � Formal parameters refer to same objects as actual parameters. � Changes to object in method are visible to invoking method. � Example � Location.midPoint(p, s); � public static Location midPoint(Location p1, Location p2) Location p x –1.0 y 0.8 Location p1 Location s x 1.7 y -1.2 Location p2 Objects and Data Abstraction (v1.05) 44 Objects as Return Values � midPoint Method—Specification public static Location midPoint(Location p1, Location p2) Generates & returns a Location halfway between two others. � Parameters p1—the first location. p2—the second location. � Returns a Location halfway between two others. � Note The answer is null if either Location is null. Objects and Data Abstraction (v1.05) 45 Objects as Return Values… � midPoint Method—Implementation public static Location midPoint(Location p1, Location p2) { double xMid, yMid; // Check whether one of the Locations is null. if ((p1 == null) || (p2 == null)) return null; // Compute the x & y midpoints. xMid = (p1.x / 2) + (p2.x / 2); yMid = (p1.y / 2) + (p2.y / 2); // Create a new Location & return it. return new Location(xMid, yMid); } Objects and Data Abstraction (v1.05) 46 Equals Method � (p == s) is true � Location p = new Location(10,2); � Location s = p; � (p != s) && p.equals(s) � Location p = new Location(10,2); � Location s = new Location(10,0); � s.shift(0,2); == vs. Equals � Operator “==” compares primitive types. � Object references are equal when they refer to the same object. � Method Equals compares objects. � Instances of the same class are equal when their instance variables have the same values. Objects and Data Abstraction (v1.05) 47 Equals Method—Implementation � Template public boolean equals(Object obj) { if (obj is actually a Location) { // Compare contents of location // referred to by obj to this // location & return value. } else return false; } � Class Location public boolean equals(Object obj) { if (obj instanceOf Location) { Location candidate = (Location obj); return (candidate.x == x) && (candidate.y == y); } else return false; } Objects and Data Abstraction (v1.05) 48 Clone Method � Creates a copy of object. � Returns reference to Object. � Must be typecast before used. � Class must implement Cloneable interface. � public class Location implements Cloneable � Should invoke clone method of superclass. � Needed for classes that are specialized. Objects and Data Abstraction (v1.05) 49 Clone Method… � Template public Object clone() { Location ans; try { ans = (Location) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException ("This class does not implement Cloneable"); } // Make necessary changes. return ans; } Objects and Data Abstraction (v1.05) 50 Clone Method… � Class Location public Object clone() { Location answer; try { answer = (Location) super.clone(); } catch (CloneNotSupportedException e) { // Exception should not occur. "implements Cloneable" may be absent // from class header. throw new RuntimeException ("This class does not implement Cloneable"); } return answer; } Objects and Data Abstraction (v1.05) 51 Class Location—Demo � Description � Creates two locations � Rotates one twice 90o. � Output The still location is at: (x=-2.0 y=-1.5) The mobile location is at: (x=-2.0 y=-1.5) Distance between them: 0.0 These two locations have equal coordinates. I will rotate one location by two 90 degree turns. The still location is at: (x=-2.0 y=-1.5) The mobile location is at: (x=2.0 y=1.5) Distance between them: 5.0 These two locations have different coordinates. Objects and Data Abstraction (v1.05) 52 Class Location—Demo… import edu.colorado.geometry.Location; class LocationDemonstration { public static void main(String[ ] args) { final double STILL_X = -2.0; final double STILL_Y = -1.5; final int ROTATIONS = 2; Location still = new Location(STILL_X, STILL_Y); Location mobile = (Location) still.clone( ); printData(still, mobile); System.out.println("I will rotate one location by two 90 degree turns."); specifiedRotation(mobile, ROTATIONS); printData(still, mobile); } // Other methods... } Objects and Data Abstraction (v1.05) 53 Class Location—Demo… // Rotate a Location p by a specified number of // 90 degree clockwise turns. public static void specifiedRotation(Location p, int n) { while (n > 0) { p.rotate90( ); n--; } } Objects and Data Abstraction (v1.05) 54 Class Location—Demo… // Print some information about two locations: // s (a "still" location) and m (a "mobile" location). public static void printData(Location s, Location m) { System.out.println ("The still location is at: " + s.toString( )); System.out.println ("The mobile location is at: " + m.toString( )); System.out.println ("Distance between them: " + Location.distance(s, m)); if (s.equals(m)) System.out.println ("These two locations have equal coordinates."); else System.out.println("These two locations have different coordinates."); System.out.println( ); }