1 / 125

Using Objects

Using Objects. Jiafan Zhou. 1. Values versus O bjects. Numbers Have values but they do not have behaviors In particular, each has only ONE value (or attribute) Objects Have attributes and behaviors An object can have multiple values (or attributes). 2. Using objects.

mort
Download Presentation

Using Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Using Objects Jiafan Zhou 1

  2. Values versus Objects • Numbers • Have values but they do not have behaviors • In particular, each has only ONE value (or attribute) • Objects • Have attributes and behaviors • An object can have multiple values (or attributes) 2

  3. 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 it 3

  4. 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.width); • System.out.println (r.height); • Objects have behaviors (or methods): • r.grow (10, 20); • r.isEmpty(); • r.setLocation (5,4); 4

  5. String Objects 5

  6. 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(); 6

  7. 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 almostthe same • There is a minor difference between the two • Which we’ll get to later 7

  8. 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 Strings 8

  9. 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. 9

  10. 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: -1 10

  11. More String methods • trim() • Returns the String without leading and trailing whitespace • Whitespace is a space, tab, or return 11

  12. 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 + "haslength" + wordLength + "."); } } 12

  13. The breakdown on objects • Objects are “things” that have properties (attributes) and behaviors (methods) • We first create one or more objects • We then manipulate their properties/fields and call their methods • In Java, properties fields are static and methods are dynamic • For example, suppose a Human object, properties such as age, gender, height and weight. Methods such as speak(), talk(), walk() and think(). Notice methods ends with parenthesis, this is a method invocation. (since it is dynamic) 13

  14. 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. 14

  15. Rectangle - width = 10 - height = 20 - ... + grow (int, int) : void + isEmpty ( ) : void + setLocation ( int, int ) : void + resize ( int, int ) : void + ... Visualizing objects • Class (type) name • Attributes (properties) • Methods (behaviors) • - sign means it is private • + sign means it is public 15

  16. 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. 16

  17. 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 of each type! • Like the difference between a recipe and a bunch of cookies 17

  18. Classes vs. Objects • A class is a user-defined “thing” • Examples: String, Scanner, Rectangle, etc. • We’ll start defining our own classes later this semester • 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 • A class is a “template” used for creating objects 18

  19. int x double d char c 7 - ‘x’ 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 stored • Note that d does not have a value 19

  20. 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 references 20

  21. 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 now) Note that there is no “new” here 21

  22. 0x0d4fe1a8 int j 5 Hello world References 2 • What’s happening in memory int j = 5; String s = “Hello world”; • Primitive types are never references; only objects int j = 5; String s = “Hello world”; String s Takes up 32 bits (4 bytes) of memory Takes up 32 bits (4 bytes) of memory At memory location 0x0d4fe1a8 Takes up 12 bytes of memory 22

  23. message 8 String peasPerPod - text = "Don't look behind the door!" - length = 27 - ... + length () : int + charAt ( int i ) : char + subString ( int m, int n ) : String + indexOf ( String s, int m ) : int + ... Representation • Statements int peasPerPod = 8; String message = "Don't look behind the door!“ 23

  24. s String - text = “I love CS 101" - length = 13 - ... + length () : int + charAt ( int i ) : char + subString ( int m, int n ) : String + indexOf ( String s, int m ) : int + ... 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); A period means “follow the reference” 24

  25. s String - text = “Hello world" - length = 11 - ... + length () : int + charAt ( int i ) : char + subString ( int m, int n ) : String + indexOf ( String s, int m ) : int + ... s “Hello world" Shorthand represntation • Consider:String s = “Hello world”; • Takes up a lot of space on my slides… • So we’ll use a shorthand representation: 25

  26. Examples • Consider String a = "excellence“; String b = a; • What is the representation? 26

  27. String s1 “first string” “second string” String s2 References 3 • Consider: String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); What happens to this? 27

  28. Java’s garbage collection • If an object in memory does not have a reference pointing to it, Java will automatically delete the object • This is really cool! • In C/C++, you had to do this by yourself 28

  29. Cleanup: finalization and garbage collection • Java has the garbage collector to reclaim the memory of objects that are no longer used. • Suppose you allocated some memory without using new keyword, then garbage collector won’t free those memory. • To handle this case, Java provides a method called finalize( ) that you can define for your class. Garbage Collector will first call finalize( ). 29

  30. Important notes • Your objects might not get garbage collected. • Garbage collection is not destruction. • Garbage collection is only about memory. • Force garbage collection: System.gc(); 30

  31. Example class Book { boolean checkedOut = false; Book(boolean checkOut) { checkedOut = checkOut; } void checkIn() { checkedOut = false; } public void finalize() { if(checkedOut) System.out.println("Error: checked out"); } } public class TerminationCodition { public static void main(String[] args) { Book novel = new Book(true); // Proper cleanup: novel.checkIn(); // Drop the reference, forget to clean up: new Book(true); // Force garbage collection & finalization: System.gc(); } } The output: “Error: checked out” 31

  32. Uninitialized versus null • Consider String dayOfWeek; Scanner inStream; • What is the representation? 32

  33. 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 there 33

  34. s String - text = “Hello world" - length = 11 - ... + length () : int + charAt ( int i ) : char + subString ( int m, int n ) : String + indexOf ( String s, int m ) : int + ... The null reference • Consider: String s = “Hello world”; System.out.println (s.length()); • What happens? • Java prints out 11 34

  35. 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: … 35

  36. What happens in Windows… 36

  37. word1 "luminous" word2 "graceful" Assignment • Consider String word1 = "luminous"; String word2 = "graceful"; word1 = word2; • Initial representation Garbage collection time! 37

  38. reponse "artiste" stdin Scanner: 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 38

  39. Final variables • Consider final String POEM_TITLE = “Appearance of Brown"; final String WARNING = “Weather ball is black"; • What is the representation? 39

  40. The reference cannot be modified once it is established LANGUAGE "Java" Final variables • Consider final String LANGUAGE = "Java"; 40

  41. int x = 3; int y = 4; The upper-left-hand int width = 5; corner of the new Rectangle int height = 2; Rectangle r = new Rectangle(x, y, width, height); The dimensions of the new Rectangle Rectangle 41

  42. 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); 42

  43. Rectangle - x = 3 - x = 3 - width = 7 - width = 1 - y = 4 - y = 4 - height = 2 - height = 2 + setWidth ( int w ) + setHeight ( int wh ) + setX ( int x ) + setY ( int y ) s + ... r Rectangle - x = 0 - x = 0 - x = 0 - width = 5 - width = 5 - width = 0 - y = 0 - y = 0 - y = 0 - height = 0 - height = 6 - height = 0 + setWidth ( int w ) Rectangle + setHeight ( int wh ) + setX ( int x ) - x = 10 - width = 8 + setY ( int y ) - y = 11 - height = 9 + ... + setWidth ( int w ) + setHeight ( int wh ) + setX ( int x ) + setY ( int y ) + ... Rectangle method usage • Consider: Rectangle r = new Rectangle(); final Rectangle s = new Rectangle (3, 4, 1, 2); r.setWidth(5); r.setHeight(6); s.setWidth (7); r = new Rectangle (10,11,8,9); s = new Rectangle (12,13,14,15); Rectangle r = new Rectangle(); final Rectangle s = new Rectangle (3, 4, 1, 2); r.setWidth(5); r.setHeight(6); s.setWidth (7); r = new Rectangle (10,11,8,9); s = new Rectangle (12,13,14,15); 43

  44. 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(); 44

  45. stdin Scanner: x 5 d 3.5 s “hello world” 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(); 45

  46. Overloading 46

  47. 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 character at index 3 up to (but not including!) the character at index 6 • 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 method overloading 47

  48. More on more on overloading • Consider the valueOf() method in the String class • String.valueOf (3) • The parameter is an int • String.valueOf (3.5) • The parameter is a double • String.valueOf (‘3’) • The parameter is a char • There are multiple versions of this method • Differentiated by their parameter list • Thus, the valueOf() method is overloaded 48

  49. Accessors/Getter • 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 it 49

  50. Mutators/Setter 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 it 50

More Related