logging in or signing up 03 using objects Estelle Download Post to : URL : Related Presentations : Share Add to Flag Embed Email Send to Blogs and Networks Add to Channel Uploaded from authorPOINTLite Insert YouTube videos in PowerPont slides with aS Desktop Copy embed code: (To copy code, click on the text box) Embed: URL: Thumbnail: WordPress Embed Customize Embed The presentation is successfully added In Your Favorites. Views: 234 Category: Entertainment License: All Rights Reserved Like it (0) Dislike it (0) Added: November 05, 2007 This Presentation is Public Favorites: 0 Presentation Description No description available. Comments Posting comment... By: rani1234 (16 month(s) ago) please send me this ppt It's very useful my email id is pradnya_borse@rediff.com Saving..... Post Reply Close Saving..... Edit Comment Close By: jocansino (39 month(s) ago) Hi, I'm jocansino from the Philippines, I'm a College instructor and i'm interested of obtaining a copy of your powerpoint slides of using objects. Can you send it to my email add at jocansino@yahoo.com. Thanks. Saving..... Post Reply Close Saving..... Edit Comment Close Premium member Presentation Transcript Using Objects: Using Objects Chapter 3 Fall 2005 CS 101 Aaron BloomfieldGetting classy: Getting classy Purpose of this chapter Gain experience creating and manipulating objects from the standard Java types Why Prepares you for defining your own classes and creating and manipulating the objects of those classesValues versus objects: Values versus objects Numbers Have values but they do not have behaviors Objects Have attributes and behaviors System.in References an InputStream Attribute: keyboard Behaviors: reading System.out References an OutputStream Attribute: monitor Behaviors: printingUsing objects: Using objects First, we create an object: Scanner stdin = new Scanner (System.in); Most object creation lines look like this Then we use the object stdin.nextInt(); stdin.nextDouble(); Note that we could have called the object foo, bar, or anything stdin is just what we chose to call itUsing Rectangle objects: Using Rectangle objects Let’s create some Rectangle objects Rectangle creation: Rectangle r = new Rectangle (10, 20); Objects have attributes (or properties): System.out.println (r.length); System.out.println (r.width); Objects have behaviors (or methods): r.grow (10, 20) r.isEmpty() r.setLocation (5,4) Using String objects: Using String objects Let’s create some String objects String creation: String s = new String (“Hello world”); Objects have attributes (or properties): But we can’t access them… Objects have behaviors (or methods): s.substring(0,6) s.indexOf (“world”) s.toLowerCase()The lowdown on objects: The lowdown on objects Objects are “things” that have properties (attributes) and behaviors (methods) We first create one or more objects We then manipulate their properties and call their methodsSo why bother with objects?: So why bother with objects? Let’s say you want to do a lot of String manipulation Once you create a String object, all the manipulation methods are contained therein Sun already wrote the methods for us So we can use String objects instead of writing our own code to get the substring, indexOf, etc.More on Strings: More on Strings Strings are used very often As a shortcut, you can use: String s = “Hello world”; instead of: String s = new String (“Hello world”); It’s just a shortcut that Java allows The two lines are almost the same There is a minor difference between the two Which we’ll get to laterVisualizing objects: Visualizing objects Class (type) name Attributes (properties) Methods (behaviors)Date translation: Date translation Goal: to translate the date from American format to standard formatEnd of lecture on 5 September 2005: End of lecture on 5 September 2005 How well do we understand using objects?: How well do we understand using objects? Sidewalk chalk guy: Sidewalk chalk guy Source: http://www.gprime.net/images/sidewalkchalkguy/Java and variables: Java and variables Consider: int x = 7; double d; char c = ‘x’; The variable name is the actual spot in memory where the value is storedWhat is a reference: What is a reference A reference is a memory address References are like pointers in C/C++ But they are not the exact same thing! C++ has references also (in addition to pointers) You may hear me call them pointers instead of references All objects in Java are declared as referencesReferences 1: References 1 Consider: int j = 5; String s = “Hello world”; Java translates that last line into: String s = new String (“Hello world”); (Not really, but close enough for this lecture) Note that there is no “new” hereReferences 2: What’s happening in memory int j = 5; String s = “Hello world”; Primitive types are never references; only objects References 2 String s Takes up 32 bits (4 bytes) of memory Takes up 32 bits (4 bytes) of memory Takes up 12 bytes of memory At memory location 0x0d4fe1a8 int j = 5; String s = “Hello world”;Other Java object types: Other Java object types String Rectangle Color JFrame Representation: Representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“Representation: Representation String s = “I love CS 101”; int l = s.length(); char c = s.charAt (3); String t = s.subString(1,2); int t = s.indexOf (t, 0);Shorthand representation: Shorthand representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“Examples: Examples Consider String a = "excellence“; String b = a; What is the representation? Uninitialized versus null: Uninitialized versus null Consider String dayOfWeek; Scanner inStream; What is the representation?Uninitialized versus null: Uninitialized versus null Consider String fontName = null; Scanner fileStream = null; What is the representation? ORThe null reference: The null reference Sometimes you want a reference to point to nothing Use the null reference: String s = null; The null reference is equivalent to a memory address of zero (0x00000000) No user program can exist thereThe null reference: The null reference Consider: String s = “Hello world”; System.out.println (s.length()); What happens? Java prints out 11Computer bugs: Computer bugsThe null reference: The null reference Consider: String s = null; System.out.println (s.length()); This is called accessing (or following) a null pointer/reference What happens? Java: java.lang.NullPointerException C/C++: Segmentation fault (core dumped) Windows: …So what is a null reference good for?: So what is a null reference good for? Let’s say you had a method that returned a String when passed some parameters Normally it returns a valid String But what if it can’t? How to deal with that? Return a null referenceReferences and memory: References and memory Most modern computers are 32-bit computers This means that a reference takes up 32 bits 232 = 4 Gb This means that a 32-bit machine cannot access more than 4 Gb of memory! Well, without doing some “tricks”, at least Most machines come with 1 Gb memory these days Will come with 4 Gb in a year or so 64-bit machines will have a maximum of 16 exabytes of memory Giga, Tera, Peta, Exa That’s 16 billion Gb!References 4: Consider: String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); References 4 What happens to this? String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2);Java’s garbage collection: Java’s garbage collection If an object in memory does not have a reference pointing to it, Java will automagically delete the object This is really cool! In C/C++, you had to do this by yourselfAssignment: Assignment Consider String word1 = "luminous"; String word2 = "graceful"; word1 = word2; Initial representation Garbage collection time!Using objects: Using objects Consider Scanner stdin = new Scanner(System.in); System.out.print("Enter your account name: "); String response = stdin.next(); Suppose the user interaction is Enter your account name: artiste String representation: String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; Standard shorthand representation Truer representation String representation: String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; char c1 = alphabet.charAt(9); char c2 = alphabet.charAt(15); char c3 = alphabet.charAt(2); What are the values of c1, c2, and c3? Why? Program WordLength.java: Program WordLength.java public class WordLength { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.print("Enter a word: "); String word = stdin.next(); int wordLength = word.length(); System.out.println("Word " + word + " has length " + wordLength + "."); } }Program demo: Program demo An optical illusion: An optical illusionMore String methods: More String methods Consider String weddingDate = "August 21, 1976"; String month = weddingDate.substring(0, 6); System.out.println("Month is " + month + "."); What is the output? Month is August.More String methods: More String methods Consider String fruit = "banana"; String searchString = "an"; int n1 = fruit.indexOf(searchString, 0); int n2 = fruit.indexOf(searchString, n1 + 1); int n3 = fruit.indexOf(searchString, n2 + 1); System.out.println("First search: " + n1); System.out.println("Second search: " + n2); System.out.println("Third search: " + n3); What is the output? First search: 1 Second search: 3 Third search: -1End of lecture 7 September 2005: End of lecture 7 September 2005 Well, that lecture sucked. Time to redo the last lecture’s worth of slides in a more coherent fashionReview: Review Variables of primitive types int, double, char, boolean, etc. Can assign a value to it Can read a value from it Can’t do much else! Objects String, Rectangle, etc. Have many parts Rectangle has width, length, etc. Like a complex type Have methods String has length(), substring(), etc.Variable declaration: Variable declaration Consider: int x = 5; int x = 7; Java won’t allow this You can only declare a variable once At the int x=7; line, Java already has a x spot in memory It can’t have twoString methods: String methods length(): returns the String’s length (duh!) String s = “hello world”; String t = “goodbye”; System.out.println (s.length()); System.out.println (t.length()); Prints 11 and 7 Note that calling s.length() is different than calling t.length()! Both return the length But of different StringsMore String methods: More String methods Consider String weddingDate = "August 21, 1976"; String month = weddingDate.substring(0, 6); System.out.println("Month is " + month + "."); What is the output? Month is August.More String methods: More String methods Consider String fruit = "banana"; String searchString = "an"; int n1 = fruit.indexOf(searchString, 0); int n2 = fruit.indexOf(searchString, n1 + 1); int n3 = fruit.indexOf(searchString, n2 + 1); System.out.println("First search: " + n1); System.out.println("Second search: " + n2); System.out.println("Third search: " + n3); What is the output? First search: 1 Second search: 3 Third search: -1Program WordLength.java: Program WordLength.java public class WordLength { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.print("Enter a word: "); String word = stdin.next(); int wordLength = word.length(); System.out.println("Word " + word + " has length " + wordLength + "."); } }Program demo: Program demo PhoneNumberFun.java: PhoneNumberFun.java import java.util.*; public class PhoneNumberFun { // main(): demonstrates a simple String manipulation public static void main(String[] args) { //... // determine the area code // determine the local number // arrange result // display input and result } } Program demo: Program demo Lots of piercings…: Lots of piercings… This may be a bit disturbing…More String methods: More String methods trim() Returns the String without leading and trailing whitespace Whitespace is a space, tab, or returnDateTranslation.java: DateTranslation.java // Convert user-specified date from American to standard format import java.util.*; class DateTranslation { // main(): application entry point static public void main(String args[]) { // produce a legend (Step 1) // prompt the user for a date in American format (Step 2) // acquire the input entered by the user (Step 3) // echo the input back (Step 4) // get month entered by the user (Step 5) // get day entered by the user (Step 6) // get year entered by the user (Step 7) // create standard format version of input (Step 8) // display the translation (Step 9) } } Program demo: Program demo Variables vs. Types: Variables vs. Types The type is the recipe or template for how to create a variable Examples: int, double, char, boolean, etc. There are only 8 primitive types There are only a few things you can do with a type: Declare a variable int x; Use it as a cast x = (int) 3.5; There is only one of each type The variable is the actual instance of a type in memory It’s a spot in memory where you store a value You choose the name: width, x, thatThemThereValue, etc. You can have as may variables as you want – but only one type! Like the difference between a recipe and a bunch of cookiesHow well do we understand variables versus types?: How well do we understand variables versus types? Classes vs. Objects: Classes vs. Objects A class is a user-defined “thing” Examples: String, Scanner, Rectangle, etc. We’ll start defining our own classes next chapter Classes are more complex than the primitive types A class is analogous to a type It’s just more complex and user-defined There can be only one class of each name An object is an instance of a class There is only one String class, but you can have 100 String objects A object is analogous to a variable It just is a reference instead A class is a “template” used for creating objectsMore on classes vs. objects: More on classes vs. objects How well do we understand classes versus objects?: How well do we understand classes versus objects? The 2004 Ig Nobel Prizes: Medicine Physics Public Health Chemistry Engineering Literature Psychology Economics Peace Biology The 2004 Ig Nobel Prizes "The Effect of Country Music on Suicide.“ For explaining the dynamics of hula-hooping Investigating the scientific validity of the Five-Second Rule The Coca-Cola Company of Great Britain For the patent of the combover The American Nudist Research Library It’s easy to overlook things – even a man in a gorilla suit. The Vatican, for outsourcing prayers to India The invention of karaoke, thereby providing an entirely new way for people to learn to tolerate each other For showing that herrings apparently communicate by fartingReferences: References Java and variables: Java and variables Consider: int x = 7; double d; char c = ‘x’; The variable name is the actual spot in memory where the value is storedWhat is a reference: What is a reference A reference is a memory address References are like pointers in C/C++ But they are not the exact same thing! C++ has references also (in addition to pointers) You may hear me call them pointers instead of references All objects in Java are declared as referencesReferences 1: References 1 Consider: int j = 5; String s = “Hello world”; Java translates that last line into: String s = new String (“Hello world”); (Not really, but close enough for this lecture) Note that there is no “new” hereReferences 2: What’s happening in memory int j = 5; String s = “Hello world”; Primitive types are never references; only objects References 2 String s Takes up 32 bits (4 bytes) of memory Takes up 32 bits (4 bytes) of memory Takes up 12 bytes of memory At memory location 0x0d4fe1a8 int j = 5; String s = “Hello world”;Representation: Representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“Representation: Representation String s = “I love CS 101”; int l = s.length(); char c = s.charAt (3); String t = s.subString(1,2); int t = s.indexOf (t, 0);Shorthand representation: Shorthand representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“Examples: Examples Consider String a = "excellence“; String b = a; What is the representation? References 3: Consider: String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); References 3 What happens to this? String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2);Java’s garbage collection: Java’s garbage collection If an object in memory does not have a reference pointing to it, Java will automagically delete the object This is really cool! In C/C++, you had to do this by yourselfEnd of lecture on 12 September 2005: End of lecture on 12 September 2005 Mary Lou also gave her talk today Want to start a few slides back to review referencesWarn your grandparents!: Warn your grandparents! Historically, this class has been lethal to grandparents of students in the class More often grandmothers This happens most around test time Although occasionally around the times a big assignment is dueUninitialized versus null: Uninitialized versus null Consider String dayOfWeek; Scanner inStream; What is the representation?Uninitialized versus null: Uninitialized versus null Consider String fontName = null; Scanner fileStream = null; What is the representation? ORThe null reference: The null reference Sometimes you want a reference to point to nothing Use the null reference: String s = null; The null reference is equivalent to a memory address of zero (0x00000000) No user program can exist thereThe null reference: The null reference Consider: String s = “Hello world”; System.out.println (s.length()); What happens? Java prints out 11The null reference: The null reference Consider: String s = null; System.out.println (s.length()); This is called accessing (or following) a null pointer/reference What happens? Java: java.lang.NullPointerException C/C++: Segmentation fault (core dumped) Windows: …What happens in Windows…: What happens in Windows…So what is a null reference good for?: So what is a null reference good for? Let’s say you had a method that returned a String when passed some parameters Normally it returns a valid String But what if it can’t? How to deal with that? Return a null referenceReferences and memory: References and memory Most modern computers are 32-bit computers This means that a reference takes up 32 bits 232 = 4 Gb This means that a 32-bit machine cannot access more than 4 Gb of memory! Well, without doing some “tricks”, at least Most machines come with 1 Gb memory these days Will come with 4 Gb in a year or so 64-bit machines will have a maximum of 16 exabytes of memory Giga, Tera, Peta, Exa That’s 16 billion Gb!Why speling is not so important…: Why speling is not so important… I cdnuolt blveieetaht I cluod aulaclty uesdnatnrd waht I was rdanieg. The phaonmneal pweor of thehmuan mind. Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is taht thefrist and lsat ltteer be in the rghit pclae. The rset can be a taotl mses andyou can sitll raed it wouthit a porbelm. Tihs is bcuseae the huamn mnid deosnot raed ervey lteter by istlef, but the wrod as a wlohe. Amzanig huh? yaeh and I awlyas thought slpeling was ipmorantt.Assignment: Assignment Consider String word1 = "luminous"; String word2 = "graceful"; word1 = word2; Initial representation Garbage collection time!Using objects: Using objects Consider Scanner stdin = new Scanner(System.in); System.out.print("Enter your account name: "); String response = stdin.next(); Suppose the user interaction is Enter your account name: artiste String representation: String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; Standard shorthand representation Truer representation String representation: String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; char c1 = alphabet.charAt(9); char c2 = alphabet.charAt(15); char c3 = alphabet.charAt(2); What are the values of c1, c2, and c3? Why? More String methods: Consider int v1 = -12; double v2 = 3.14; char v3 = 'a'; String s1 = String.valueOf(v1); String s2 = String.valueOf(v2); String s3 = String.valueOf(v3); int v1 = -12; double v2 = 3.14; char v3 = 'a'; String s1 = String.valueOf(v1); String s2 = String.valueOf(v2); String s3 = String.valueOf(v3); More String methodsJust in time for Valentine’s Day…: Just in time for Valentine’s Day…Bittersweets: Dejected sayings: Bittersweets: Dejected sayings I MISS MY EX PEAKED AT 17 MAIL ORDER TABLE FOR 1 I CRY ON Q U C MY BLOG? REJECT PILE PILLOW HUGGIN ASYLUM BOUND DIGNITY FREE PROG FAN STATIC CLING WE HAD PLANS XANADU 2NITE SETTLE 4LESS NOT AGAIN Bittersweets: Dysfunctional sayings: Bittersweets: Dysfunctional sayings RUMORS TRUE PRENUP OKAY? HE CAN LISTEN GAME ON TV CALL A 900# P.S. I LUV ME DO MY DISHES UWATCH CMT PAROLE IS UP! BE MY YOKO U+ME=GRIEF I WANT HALF RETURN 2 PIT NOT MY MOMMY BE MY PRISON C THAT DOOR? Final variables: Final variables Consider final String POEM_TITLE = “Appearance of Brown"; final String WARNING = “Weather ball is black"; What is the representation?Final variables: Final variablesRectangle: RectangleFinal variables: Final variables Consider final String LANGUAGE = "Java"; Rectangle: Consider final Rectangle BLOCK = new Rectangle(6, 9, 4, 2); BLOCK.setLocation(1, 4); BLOCK.resize(8, 3); final Rectangle BLOCK = new Rectangle(6, 9, 4, 2); BLOCK.setLocation(1, 4); BLOCK.resize(8, 3); RectangleString method usage: Consider: String s = "Halloween"; String t = "Groundhog Day"; String u = "May Day"; String v = s.substring(0,6); int x = t.indexOf ("Day", 0); int y = u.indexOf ("Day"); s = t; u = null; String method usage String s = "Halloween"; String t = "Groundhog Day"; String u = "May Day"; String v = s.substring(0,6); int x = t.indexOf ("Day", 0); int y = u.indexOf ("Day"); s = t; u = null;String method usage: Consider: String s = "Halloween"; String t = "Groundhog Day"; final String u = "May Day"; String v = s.substring(0,6); int x = t.indexOf ("Day", 0); int y = u.indexOf ("Day"); s = t; u = null; String method usage s = t; u = null; Java error: cannot assign a value to final variable uRectangle method usage: Rectangle method usage Consider: Rectangle r = new Rectangle(); final Rectangle s = new Rectangle (1, 2, 3, 4); r.setWidth(5); r.setHeight(6); s.setWidth (7); r = new Rectangle (8,9,10,11); s = new Rectangle (12,13,14,15); Rectangle r = new Rectangle(); final Rectangle s = new Rectangle (1, 2, 3, 4); r.setWidth(5); r.setHeight(6); s.setWidth (7); r = new Rectangle (8,9,10,11); s = new Rectangle (12,13,14,15);Scanner review: Scanner review To initialize a Scanner object: Scanner stdin = new Scanner (System.in); Scanner stdin = Scanner.create (System.in); This one will not work! To read an int from the keyboard: stdin.nextInt(); To read a double from the keyboard: stdin.nextDouble(); To read a String from the keyboard: stdin.next();Scanner usage examples: Scanner usage examples Consider: Scanner stdin = new Scanner (System.in); int x = stdin.nextInt(); double d = stdin.nextDouble(); String s = stdin.next(); Scanner stdin = new Scanner (System.in); int x = stdin.nextInt(); double d = stdin.nextDouble(); String s = stdin.next();Today’s demotivators: Today’s demotivatorsEnd of lecture on 14 Sep 2005: End of lecture on 14 Sep 2005 We also did the first few slides of chapter 5 The remaining slides in this set were done on 19 Sep 2005Overloading: Overloading We’ve seen a number of methods In the String class: substring(), charAt(), indexOf(), etc. In the Rectangle class: setLocation(), translate() Consider the substring() method in the String class One version: s.substring(3) This will return a string from the 4th character on Another version: s.substring (3,6) This version will return a string from the 3rd to the 5th character There are multiple versions of the same method Differentiated by their parameter list The substring method can take one OR two parameters This is called overloadingMore on overloading: More on overloading Consider the ‘+’ operator It can mean integer addition: 3+5 = 8 It can mean floating-point addition: 3.0+5.0 = 8.0 It can mean string concatenation: “foo” + “bar” = “foobar” The ‘+’ operator has multiple “things” it can do a.k.a. the ‘+’ operator is overloadedMore on more on overloading: More on more on overloading Consider the valueOf() method in the String class s.valueOf (3) The parameter is an int s.valueOf (3.5) The parameter is a double s.valueOf (‘3’) The parameter is a char There are multiple versions of this method Differentiated by their parameter list Thus, the valueOf() method is overloadedAccessors: Accessors Some methods allow us to find out information about an object In the Rectangle class: getWidth(), getHeight() These methods are called accessors They allow us to access attributes of the object An accessor is a method that allows us to find out attributes of object Usually start with get in the method name I won’t use this terminology much, but the book uses itMutators: Mutators Some methods allow us to set information about the object In the Rectangle class: setLocation(), setBounds() These methods are called mutators They allow us to change (or mutate) the attributes of an object A mutator is a method that allows us to set attributes of object Usually start with set in the method name I won’t use this terminology much, but the book uses itConstructors: Constructors A constructor is a special method called ONLY when you are creating (or constructing) and object The name of the constructor is ALWAYS the exact same name as the class Scanner stdin = new Scanner (System.in); String foo = new String (“hello world”); There can be overloaded constructors Rectangle r = new Rectangle(); Rectangle s = new Rectangle (1, 2, 3, 4); Calling the Circle constructor: Calling the Circle constructor To create a Circle object: Circle c1 = new Circle(); This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object Calls the constructor with no parameters (the ‘default’ constructor) The constructor is always the first method called when creating (or ‘constructing’) an object Calling the Circle constructor: Calling the Circle constructor To create a Circle object: Circle c1 = new Circle(2.0); This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object Calls the constructor with 1 double parameters (the ‘specific’ constructor) The constructor is always the first method called when creating (or ‘constructing’) an object Constructor varieties: Constructor varieties The default constructor usually sets the attributes of an object to default values But that’s not why it’s called default (we’ll get to that later) The default constructor ALWAYS takes in zero parameters Thus, there can be only one A specific constructor sets the attributes of the object to the passed values We’ll get to why it’s called a specific constructor later The specific constructor takes in one or more parameters There can be more than one (via overloading)Method types review: Method types review With the exception of constructors, these names are purely for human categorization Accessor: allows one to access parts of the object Mutator: allows one to change (mutate) a part of an object Constructor: used to create a object Default constructor: takes in no parameters Specific constructor: takes in one or more parameters Facilitator Any method that is not one of the above You do not have the permission to view this presentation. In order to view it, please contact the author of the presentation.
03 using objects Estelle Download Post to : URL : Related Presentations : Share Add to Flag Embed Email Send to Blogs and Networks Add to Channel Uploaded from authorPOINTLite Insert YouTube videos in PowerPont slides with aS Desktop Copy embed code: (To copy code, click on the text box) Embed: URL: Thumbnail: WordPress Embed Customize Embed The presentation is successfully added In Your Favorites. Views: 234 Category: Entertainment License: All Rights Reserved Like it (0) Dislike it (0) Added: November 05, 2007 This Presentation is Public Favorites: 0 Presentation Description No description available. Comments Posting comment... By: rani1234 (16 month(s) ago) please send me this ppt It's very useful my email id is pradnya_borse@rediff.com Saving..... Post Reply Close Saving..... Edit Comment Close By: jocansino (39 month(s) ago) Hi, I'm jocansino from the Philippines, I'm a College instructor and i'm interested of obtaining a copy of your powerpoint slides of using objects. Can you send it to my email add at jocansino@yahoo.com. Thanks. Saving..... Post Reply Close Saving..... Edit Comment Close Premium member Presentation Transcript Using Objects: Using Objects Chapter 3 Fall 2005 CS 101 Aaron BloomfieldGetting classy: Getting classy Purpose of this chapter Gain experience creating and manipulating objects from the standard Java types Why Prepares you for defining your own classes and creating and manipulating the objects of those classesValues versus objects: Values versus objects Numbers Have values but they do not have behaviors Objects Have attributes and behaviors System.in References an InputStream Attribute: keyboard Behaviors: reading System.out References an OutputStream Attribute: monitor Behaviors: printingUsing objects: Using objects First, we create an object: Scanner stdin = new Scanner (System.in); Most object creation lines look like this Then we use the object stdin.nextInt(); stdin.nextDouble(); Note that we could have called the object foo, bar, or anything stdin is just what we chose to call itUsing Rectangle objects: Using Rectangle objects Let’s create some Rectangle objects Rectangle creation: Rectangle r = new Rectangle (10, 20); Objects have attributes (or properties): System.out.println (r.length); System.out.println (r.width); Objects have behaviors (or methods): r.grow (10, 20) r.isEmpty() r.setLocation (5,4) Using String objects: Using String objects Let’s create some String objects String creation: String s = new String (“Hello world”); Objects have attributes (or properties): But we can’t access them… Objects have behaviors (or methods): s.substring(0,6) s.indexOf (“world”) s.toLowerCase()The lowdown on objects: The lowdown on objects Objects are “things” that have properties (attributes) and behaviors (methods) We first create one or more objects We then manipulate their properties and call their methodsSo why bother with objects?: So why bother with objects? Let’s say you want to do a lot of String manipulation Once you create a String object, all the manipulation methods are contained therein Sun already wrote the methods for us So we can use String objects instead of writing our own code to get the substring, indexOf, etc.More on Strings: More on Strings Strings are used very often As a shortcut, you can use: String s = “Hello world”; instead of: String s = new String (“Hello world”); It’s just a shortcut that Java allows The two lines are almost the same There is a minor difference between the two Which we’ll get to laterVisualizing objects: Visualizing objects Class (type) name Attributes (properties) Methods (behaviors)Date translation: Date translation Goal: to translate the date from American format to standard formatEnd of lecture on 5 September 2005: End of lecture on 5 September 2005 How well do we understand using objects?: How well do we understand using objects? Sidewalk chalk guy: Sidewalk chalk guy Source: http://www.gprime.net/images/sidewalkchalkguy/Java and variables: Java and variables Consider: int x = 7; double d; char c = ‘x’; The variable name is the actual spot in memory where the value is storedWhat is a reference: What is a reference A reference is a memory address References are like pointers in C/C++ But they are not the exact same thing! C++ has references also (in addition to pointers) You may hear me call them pointers instead of references All objects in Java are declared as referencesReferences 1: References 1 Consider: int j = 5; String s = “Hello world”; Java translates that last line into: String s = new String (“Hello world”); (Not really, but close enough for this lecture) Note that there is no “new” hereReferences 2: What’s happening in memory int j = 5; String s = “Hello world”; Primitive types are never references; only objects References 2 String s Takes up 32 bits (4 bytes) of memory Takes up 32 bits (4 bytes) of memory Takes up 12 bytes of memory At memory location 0x0d4fe1a8 int j = 5; String s = “Hello world”;Other Java object types: Other Java object types String Rectangle Color JFrame Representation: Representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“Representation: Representation String s = “I love CS 101”; int l = s.length(); char c = s.charAt (3); String t = s.subString(1,2); int t = s.indexOf (t, 0);Shorthand representation: Shorthand representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“Examples: Examples Consider String a = "excellence“; String b = a; What is the representation? Uninitialized versus null: Uninitialized versus null Consider String dayOfWeek; Scanner inStream; What is the representation?Uninitialized versus null: Uninitialized versus null Consider String fontName = null; Scanner fileStream = null; What is the representation? ORThe null reference: The null reference Sometimes you want a reference to point to nothing Use the null reference: String s = null; The null reference is equivalent to a memory address of zero (0x00000000) No user program can exist thereThe null reference: The null reference Consider: String s = “Hello world”; System.out.println (s.length()); What happens? Java prints out 11Computer bugs: Computer bugsThe null reference: The null reference Consider: String s = null; System.out.println (s.length()); This is called accessing (or following) a null pointer/reference What happens? Java: java.lang.NullPointerException C/C++: Segmentation fault (core dumped) Windows: …So what is a null reference good for?: So what is a null reference good for? Let’s say you had a method that returned a String when passed some parameters Normally it returns a valid String But what if it can’t? How to deal with that? Return a null referenceReferences and memory: References and memory Most modern computers are 32-bit computers This means that a reference takes up 32 bits 232 = 4 Gb This means that a 32-bit machine cannot access more than 4 Gb of memory! Well, without doing some “tricks”, at least Most machines come with 1 Gb memory these days Will come with 4 Gb in a year or so 64-bit machines will have a maximum of 16 exabytes of memory Giga, Tera, Peta, Exa That’s 16 billion Gb!References 4: Consider: String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); References 4 What happens to this? String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2);Java’s garbage collection: Java’s garbage collection If an object in memory does not have a reference pointing to it, Java will automagically delete the object This is really cool! In C/C++, you had to do this by yourselfAssignment: Assignment Consider String word1 = "luminous"; String word2 = "graceful"; word1 = word2; Initial representation Garbage collection time!Using objects: Using objects Consider Scanner stdin = new Scanner(System.in); System.out.print("Enter your account name: "); String response = stdin.next(); Suppose the user interaction is Enter your account name: artiste String representation: String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; Standard shorthand representation Truer representation String representation: String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; char c1 = alphabet.charAt(9); char c2 = alphabet.charAt(15); char c3 = alphabet.charAt(2); What are the values of c1, c2, and c3? Why? Program WordLength.java: Program WordLength.java public class WordLength { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.print("Enter a word: "); String word = stdin.next(); int wordLength = word.length(); System.out.println("Word " + word + " has length " + wordLength + "."); } }Program demo: Program demo An optical illusion: An optical illusionMore String methods: More String methods Consider String weddingDate = "August 21, 1976"; String month = weddingDate.substring(0, 6); System.out.println("Month is " + month + "."); What is the output? Month is August.More String methods: More String methods Consider String fruit = "banana"; String searchString = "an"; int n1 = fruit.indexOf(searchString, 0); int n2 = fruit.indexOf(searchString, n1 + 1); int n3 = fruit.indexOf(searchString, n2 + 1); System.out.println("First search: " + n1); System.out.println("Second search: " + n2); System.out.println("Third search: " + n3); What is the output? First search: 1 Second search: 3 Third search: -1End of lecture 7 September 2005: End of lecture 7 September 2005 Well, that lecture sucked. Time to redo the last lecture’s worth of slides in a more coherent fashionReview: Review Variables of primitive types int, double, char, boolean, etc. Can assign a value to it Can read a value from it Can’t do much else! Objects String, Rectangle, etc. Have many parts Rectangle has width, length, etc. Like a complex type Have methods String has length(), substring(), etc.Variable declaration: Variable declaration Consider: int x = 5; int x = 7; Java won’t allow this You can only declare a variable once At the int x=7; line, Java already has a x spot in memory It can’t have twoString methods: String methods length(): returns the String’s length (duh!) String s = “hello world”; String t = “goodbye”; System.out.println (s.length()); System.out.println (t.length()); Prints 11 and 7 Note that calling s.length() is different than calling t.length()! Both return the length But of different StringsMore String methods: More String methods Consider String weddingDate = "August 21, 1976"; String month = weddingDate.substring(0, 6); System.out.println("Month is " + month + "."); What is the output? Month is August.More String methods: More String methods Consider String fruit = "banana"; String searchString = "an"; int n1 = fruit.indexOf(searchString, 0); int n2 = fruit.indexOf(searchString, n1 + 1); int n3 = fruit.indexOf(searchString, n2 + 1); System.out.println("First search: " + n1); System.out.println("Second search: " + n2); System.out.println("Third search: " + n3); What is the output? First search: 1 Second search: 3 Third search: -1Program WordLength.java: Program WordLength.java public class WordLength { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.print("Enter a word: "); String word = stdin.next(); int wordLength = word.length(); System.out.println("Word " + word + " has length " + wordLength + "."); } }Program demo: Program demo PhoneNumberFun.java: PhoneNumberFun.java import java.util.*; public class PhoneNumberFun { // main(): demonstrates a simple String manipulation public static void main(String[] args) { //... // determine the area code // determine the local number // arrange result // display input and result } } Program demo: Program demo Lots of piercings…: Lots of piercings… This may be a bit disturbing…More String methods: More String methods trim() Returns the String without leading and trailing whitespace Whitespace is a space, tab, or returnDateTranslation.java: DateTranslation.java // Convert user-specified date from American to standard format import java.util.*; class DateTranslation { // main(): application entry point static public void main(String args[]) { // produce a legend (Step 1) // prompt the user for a date in American format (Step 2) // acquire the input entered by the user (Step 3) // echo the input back (Step 4) // get month entered by the user (Step 5) // get day entered by the user (Step 6) // get year entered by the user (Step 7) // create standard format version of input (Step 8) // display the translation (Step 9) } } Program demo: Program demo Variables vs. Types: Variables vs. Types The type is the recipe or template for how to create a variable Examples: int, double, char, boolean, etc. There are only 8 primitive types There are only a few things you can do with a type: Declare a variable int x; Use it as a cast x = (int) 3.5; There is only one of each type The variable is the actual instance of a type in memory It’s a spot in memory where you store a value You choose the name: width, x, thatThemThereValue, etc. You can have as may variables as you want – but only one type! Like the difference between a recipe and a bunch of cookiesHow well do we understand variables versus types?: How well do we understand variables versus types? Classes vs. Objects: Classes vs. Objects A class is a user-defined “thing” Examples: String, Scanner, Rectangle, etc. We’ll start defining our own classes next chapter Classes are more complex than the primitive types A class is analogous to a type It’s just more complex and user-defined There can be only one class of each name An object is an instance of a class There is only one String class, but you can have 100 String objects A object is analogous to a variable It just is a reference instead A class is a “template” used for creating objectsMore on classes vs. objects: More on classes vs. objects How well do we understand classes versus objects?: How well do we understand classes versus objects? The 2004 Ig Nobel Prizes: Medicine Physics Public Health Chemistry Engineering Literature Psychology Economics Peace Biology The 2004 Ig Nobel Prizes "The Effect of Country Music on Suicide.“ For explaining the dynamics of hula-hooping Investigating the scientific validity of the Five-Second Rule The Coca-Cola Company of Great Britain For the patent of the combover The American Nudist Research Library It’s easy to overlook things – even a man in a gorilla suit. The Vatican, for outsourcing prayers to India The invention of karaoke, thereby providing an entirely new way for people to learn to tolerate each other For showing that herrings apparently communicate by fartingReferences: References Java and variables: Java and variables Consider: int x = 7; double d; char c = ‘x’; The variable name is the actual spot in memory where the value is storedWhat is a reference: What is a reference A reference is a memory address References are like pointers in C/C++ But they are not the exact same thing! C++ has references also (in addition to pointers) You may hear me call them pointers instead of references All objects in Java are declared as referencesReferences 1: References 1 Consider: int j = 5; String s = “Hello world”; Java translates that last line into: String s = new String (“Hello world”); (Not really, but close enough for this lecture) Note that there is no “new” hereReferences 2: What’s happening in memory int j = 5; String s = “Hello world”; Primitive types are never references; only objects References 2 String s Takes up 32 bits (4 bytes) of memory Takes up 32 bits (4 bytes) of memory Takes up 12 bytes of memory At memory location 0x0d4fe1a8 int j = 5; String s = “Hello world”;Representation: Representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“Representation: Representation String s = “I love CS 101”; int l = s.length(); char c = s.charAt (3); String t = s.subString(1,2); int t = s.indexOf (t, 0);Shorthand representation: Shorthand representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“Examples: Examples Consider String a = "excellence“; String b = a; What is the representation? References 3: Consider: String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); References 3 What happens to this? String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2);Java’s garbage collection: Java’s garbage collection If an object in memory does not have a reference pointing to it, Java will automagically delete the object This is really cool! In C/C++, you had to do this by yourselfEnd of lecture on 12 September 2005: End of lecture on 12 September 2005 Mary Lou also gave her talk today Want to start a few slides back to review referencesWarn your grandparents!: Warn your grandparents! Historically, this class has been lethal to grandparents of students in the class More often grandmothers This happens most around test time Although occasionally around the times a big assignment is dueUninitialized versus null: Uninitialized versus null Consider String dayOfWeek; Scanner inStream; What is the representation?Uninitialized versus null: Uninitialized versus null Consider String fontName = null; Scanner fileStream = null; What is the representation? ORThe null reference: The null reference Sometimes you want a reference to point to nothing Use the null reference: String s = null; The null reference is equivalent to a memory address of zero (0x00000000) No user program can exist thereThe null reference: The null reference Consider: String s = “Hello world”; System.out.println (s.length()); What happens? Java prints out 11The null reference: The null reference Consider: String s = null; System.out.println (s.length()); This is called accessing (or following) a null pointer/reference What happens? Java: java.lang.NullPointerException C/C++: Segmentation fault (core dumped) Windows: …What happens in Windows…: What happens in Windows…So what is a null reference good for?: So what is a null reference good for? Let’s say you had a method that returned a String when passed some parameters Normally it returns a valid String But what if it can’t? How to deal with that? Return a null referenceReferences and memory: References and memory Most modern computers are 32-bit computers This means that a reference takes up 32 bits 232 = 4 Gb This means that a 32-bit machine cannot access more than 4 Gb of memory! Well, without doing some “tricks”, at least Most machines come with 1 Gb memory these days Will come with 4 Gb in a year or so 64-bit machines will have a maximum of 16 exabytes of memory Giga, Tera, Peta, Exa That’s 16 billion Gb!Why speling is not so important…: Why speling is not so important… I cdnuolt blveieetaht I cluod aulaclty uesdnatnrd waht I was rdanieg. The phaonmneal pweor of thehmuan mind. Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is taht thefrist and lsat ltteer be in the rghit pclae. The rset can be a taotl mses andyou can sitll raed it wouthit a porbelm. Tihs is bcuseae the huamn mnid deosnot raed ervey lteter by istlef, but the wrod as a wlohe. Amzanig huh? yaeh and I awlyas thought slpeling was ipmorantt.Assignment: Assignment Consider String word1 = "luminous"; String word2 = "graceful"; word1 = word2; Initial representation Garbage collection time!Using objects: Using objects Consider Scanner stdin = new Scanner(System.in); System.out.print("Enter your account name: "); String response = stdin.next(); Suppose the user interaction is Enter your account name: artiste String representation: String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; Standard shorthand representation Truer representation String representation: String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; char c1 = alphabet.charAt(9); char c2 = alphabet.charAt(15); char c3 = alphabet.charAt(2); What are the values of c1, c2, and c3? Why? More String methods: Consider int v1 = -12; double v2 = 3.14; char v3 = 'a'; String s1 = String.valueOf(v1); String s2 = String.valueOf(v2); String s3 = String.valueOf(v3); int v1 = -12; double v2 = 3.14; char v3 = 'a'; String s1 = String.valueOf(v1); String s2 = String.valueOf(v2); String s3 = String.valueOf(v3); More String methodsJust in time for Valentine’s Day…: Just in time for Valentine’s Day…Bittersweets: Dejected sayings: Bittersweets: Dejected sayings I MISS MY EX PEAKED AT 17 MAIL ORDER TABLE FOR 1 I CRY ON Q U C MY BLOG? REJECT PILE PILLOW HUGGIN ASYLUM BOUND DIGNITY FREE PROG FAN STATIC CLING WE HAD PLANS XANADU 2NITE SETTLE 4LESS NOT AGAIN Bittersweets: Dysfunctional sayings: Bittersweets: Dysfunctional sayings RUMORS TRUE PRENUP OKAY? HE CAN LISTEN GAME ON TV CALL A 900# P.S. I LUV ME DO MY DISHES UWATCH CMT PAROLE IS UP! BE MY YOKO U+ME=GRIEF I WANT HALF RETURN 2 PIT NOT MY MOMMY BE MY PRISON C THAT DOOR? Final variables: Final variables Consider final String POEM_TITLE = “Appearance of Brown"; final String WARNING = “Weather ball is black"; What is the representation?Final variables: Final variablesRectangle: RectangleFinal variables: Final variables Consider final String LANGUAGE = "Java"; Rectangle: Consider final Rectangle BLOCK = new Rectangle(6, 9, 4, 2); BLOCK.setLocation(1, 4); BLOCK.resize(8, 3); final Rectangle BLOCK = new Rectangle(6, 9, 4, 2); BLOCK.setLocation(1, 4); BLOCK.resize(8, 3); RectangleString method usage: Consider: String s = "Halloween"; String t = "Groundhog Day"; String u = "May Day"; String v = s.substring(0,6); int x = t.indexOf ("Day", 0); int y = u.indexOf ("Day"); s = t; u = null; String method usage String s = "Halloween"; String t = "Groundhog Day"; String u = "May Day"; String v = s.substring(0,6); int x = t.indexOf ("Day", 0); int y = u.indexOf ("Day"); s = t; u = null;String method usage: Consider: String s = "Halloween"; String t = "Groundhog Day"; final String u = "May Day"; String v = s.substring(0,6); int x = t.indexOf ("Day", 0); int y = u.indexOf ("Day"); s = t; u = null; String method usage s = t; u = null; Java error: cannot assign a value to final variable uRectangle method usage: Rectangle method usage Consider: Rectangle r = new Rectangle(); final Rectangle s = new Rectangle (1, 2, 3, 4); r.setWidth(5); r.setHeight(6); s.setWidth (7); r = new Rectangle (8,9,10,11); s = new Rectangle (12,13,14,15); Rectangle r = new Rectangle(); final Rectangle s = new Rectangle (1, 2, 3, 4); r.setWidth(5); r.setHeight(6); s.setWidth (7); r = new Rectangle (8,9,10,11); s = new Rectangle (12,13,14,15);Scanner review: Scanner review To initialize a Scanner object: Scanner stdin = new Scanner (System.in); Scanner stdin = Scanner.create (System.in); This one will not work! To read an int from the keyboard: stdin.nextInt(); To read a double from the keyboard: stdin.nextDouble(); To read a String from the keyboard: stdin.next();Scanner usage examples: Scanner usage examples Consider: Scanner stdin = new Scanner (System.in); int x = stdin.nextInt(); double d = stdin.nextDouble(); String s = stdin.next(); Scanner stdin = new Scanner (System.in); int x = stdin.nextInt(); double d = stdin.nextDouble(); String s = stdin.next();Today’s demotivators: Today’s demotivatorsEnd of lecture on 14 Sep 2005: End of lecture on 14 Sep 2005 We also did the first few slides of chapter 5 The remaining slides in this set were done on 19 Sep 2005Overloading: Overloading We’ve seen a number of methods In the String class: substring(), charAt(), indexOf(), etc. In the Rectangle class: setLocation(), translate() Consider the substring() method in the String class One version: s.substring(3) This will return a string from the 4th character on Another version: s.substring (3,6) This version will return a string from the 3rd to the 5th character There are multiple versions of the same method Differentiated by their parameter list The substring method can take one OR two parameters This is called overloadingMore on overloading: More on overloading Consider the ‘+’ operator It can mean integer addition: 3+5 = 8 It can mean floating-point addition: 3.0+5.0 = 8.0 It can mean string concatenation: “foo” + “bar” = “foobar” The ‘+’ operator has multiple “things” it can do a.k.a. the ‘+’ operator is overloadedMore on more on overloading: More on more on overloading Consider the valueOf() method in the String class s.valueOf (3) The parameter is an int s.valueOf (3.5) The parameter is a double s.valueOf (‘3’) The parameter is a char There are multiple versions of this method Differentiated by their parameter list Thus, the valueOf() method is overloadedAccessors: Accessors Some methods allow us to find out information about an object In the Rectangle class: getWidth(), getHeight() These methods are called accessors They allow us to access attributes of the object An accessor is a method that allows us to find out attributes of object Usually start with get in the method name I won’t use this terminology much, but the book uses itMutators: Mutators Some methods allow us to set information about the object In the Rectangle class: setLocation(), setBounds() These methods are called mutators They allow us to change (or mutate) the attributes of an object A mutator is a method that allows us to set attributes of object Usually start with set in the method name I won’t use this terminology much, but the book uses itConstructors: Constructors A constructor is a special method called ONLY when you are creating (or constructing) and object The name of the constructor is ALWAYS the exact same name as the class Scanner stdin = new Scanner (System.in); String foo = new String (“hello world”); There can be overloaded constructors Rectangle r = new Rectangle(); Rectangle s = new Rectangle (1, 2, 3, 4); Calling the Circle constructor: Calling the Circle constructor To create a Circle object: Circle c1 = new Circle(); This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object Calls the constructor with no parameters (the ‘default’ constructor) The constructor is always the first method called when creating (or ‘constructing’) an object Calling the Circle constructor: Calling the Circle constructor To create a Circle object: Circle c1 = new Circle(2.0); This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object Calls the constructor with 1 double parameters (the ‘specific’ constructor) The constructor is always the first method called when creating (or ‘constructing’) an object Constructor varieties: Constructor varieties The default constructor usually sets the attributes of an object to default values But that’s not why it’s called default (we’ll get to that later) The default constructor ALWAYS takes in zero parameters Thus, there can be only one A specific constructor sets the attributes of the object to the passed values We’ll get to why it’s called a specific constructor later The specific constructor takes in one or more parameters There can be more than one (via overloading)Method types review: Method types review With the exception of constructors, these names are purely for human categorization Accessor: allows one to access parts of the object Mutator: allows one to change (mutate) a part of an object Constructor: used to create a object Default constructor: takes in no parameters Specific constructor: takes in one or more parameters Facilitator Any method that is not one of the above