Section 3 3 Using Objects So far we
Section 3. 3 Using Objects So far, we have seen: methods, which represent code to do something variables, which represent data (categorized by types) It is possible to create new types that contain both variables and methods. Such types are called object types. Languages such as Java in which you can do this are called objectoriented programming languages. In Chapter 3 we start learning how to use some of Java's built in objects. In Chapter 8 we will learn to create our own types of objects.
class: • The code that declares a group of variables and the associated methods for manipulating those variables. • A class is a template from which objects are built. • A class has no physical existence, it occupies no space in memory. (int itself occupies no space, int x; x occupies space. ) • Java contains many predefined classes § Examples: o The class String represents objects that store text characters and has methods for searching and selecting. o The class Point represents objects that store (x, y) data and has methods for calculating distance, and moving. o The class Color represents objects that hold the amounts of reg, green, and blue in a color and has methods for brightening and darkening • A class is a new type that you can define to do what you want it to do.
object: A particular instance of a class. An object is defined by its class. An object occupies space in memory. An object’s contents are defined by its class. An object contains data and behavior. • There are variables inside the object, representing its data. • There are methods inside the object, representing its behavior. An object is a compound variable made up of a variety of other variables and methods. 4
Most objects are constructed with the new keyword. <type> <name> = new <type> ( <parameters> ); Examples: Point pt = new Point(7, -4); Color orange = new Color(255, 128, 0); Drawing. Panel p = new Drawing. Panel(300, 200); Convention: class names start with a capital letter (e. g. Point) Strings are also objects, but are constructed without new : String name = "Amelia Bedelia";
6
Examples: • The Math class contains the methods for sqrt, abs, log, etc. Math is a little different than other classes in that you never instantiate an object of type Math. • The class String represents objects that store text characters and contains methods that perform operations on objects of type String my. String = “This is a string”; // Creates a String object System. out. println(my. String); // prints: This is a string length() is method that returns the length of the string. int my. String. Length; my. String. Length = my. String. length(); // my. String. Length is 16 7
Constructing objects • construct: To create a new object. – Objects are constructed with the new keyword. – Most objects must be constructed before they can be used. • Constructing objects, general syntax: <type> <name> = new <type> ( <parameters> ); – Examples (that are not expected to be completely understandable right now): Point p = new Point(7, -4); Drawing. Panel window = new Drawing. Panel(300, 200); Color orange = new Color(255, 128, 0); – Classes' names are usually uppercase (e. g. Point, Color). – Strings are also objects, but are constructed without new : String name = "Amanda Ann Camp"; 8
• Objects contain methods that can be called by your program. – For example, a String's methods manipulate or process text in that String in useful ways. – When we call an object's method, we are sending a message to it. – We must specify which object we are talking to, and then write the method's name. • Calling a method of an object, general syntax: <object>. <method name> ( <parameters> ) 9
– Examples: String my. Dogs = “Corky and Meg"; System. out. println(my. Dogs. length()); // 13 Point p 1 = new Point(3, 4); Point p 2 = new Point(0, 0); double how. Far = p 1. distance(p 2)); //how. Far = 5. 0 Why? 10
11
Data stored in each Point object: Field name x y Description the point's x-coordinate the point's y-coordinate Useful methods of Point objects: Method name Description distance(p) how far away the point is from point p set. Location(x, y) sets the point's x and y to the given values translate(dx, dy) adjusts the point's x and y by given amounts
Point objects can also be printed using println statements: Point p = new Point(5, -2); System. out. println(p); Output: java. awt. Point[x=5, y=-2] • System. out. println(p. x “ “ + p. y); Output: 5 -2 • Point p 1 = new Point(3, 4); Point p 2 = new Point(0, 0); double how. Far = p 1. distance(p 2)); //how. Far = 5. 0 // Why? 13
String indexing Given String greedy = “This is mine. ”; T h i s mi n e . 0 1 2 3 4 5 6 7 8 9 10 11 12 characters indices Each character in the string is stored at a place numbered from 0 to the length of the string -1. This number is called its index. There is a String method named char. At() that returns the character at a specific index in the string. char 7 = greedy. char. At(6); // char 7 contains ‘s’. 14
String methods • Given the following string: String book = "Building Java Programs"; How would you extract the word "Java" ? book. substring(9, 13) How would you change book to store: "BUILDING JAVA PROGRAMS" ? book=book. to. Upper. Case(); – How would you extract the first word from any general string? my. String. substring(0, my. String. index. Of(“ “)) Method name char. At(index) Description character at a specific index. Of(str) index where the start of the given string appears in this string (-1 if it is not there) length() number of characters in this string substring(index 1, index 2) the characters in this string from index 1 (inclusive) to index 2 (exclusive) to. Lower. Case() a new string with all lowercase letters to. Upper. Case() a new string with all uppercase letters 15
String method examples // 11 // index 012345678901 String s 1 = "Stuart Reges"; String s 2 = "Marty Stepp"; System. out. println(s 1. length()); System. out. println(s 1. index. Of("e")); System. out. println(s 1. substring(1, 4)); // 12 // 8 // tua String s 3 = s 2. to. Upper. Case(); System. out. println(s 3. substring(6, 10)); // STEP String s 4 = s 1. substring(0, 6); System. out. println(s 4. to. Lower. Case()); // stuart
The String type is called immutable because Strings can not be modified! The methods that appear to modify a string: substring, to. Lower. Case, to. Upper. Case, . . . actually create and return a new string. String s = "I am immutable"; s. to. Upper. Case(); System. out. println(s); // output: I am immutable If you want to modify the variable, you must reassign it to store the result of the method call: String s = "I am immutable"; s = s. to. Upper. Case(); System. out. println(s); // output: I AM IMMUTABLE
Common error - Not using the result of a method call Ex. book. to. Upper. Case(); // Legal Java statement Returns the string "BUILDING JAVA PROGRAMS" but does not change the object book. Need to say book = book. to. Upper. Case(); This replaces the string in book with the result of calling book. to. Upper. Case(). e. g. , i + 1; does not change i but i = i + 1; does 18
• Reference semantics With primitive types, the value of the variable is stored in the place given by that variable’s name. int x = 8; // x 8 With objects, the place in memory named by that object does not contain the objects value but a reference (memory address) of the place that actually stores the object. String greedy = “This is mine. ”; // greedy This is mine. • Efficiency and sharing It is frequently adequate (or even preferred) to share an object rather than having multiple copies of it. References allow this. String share = greedy; // share The reference value in greedy is copied into share. 19
Objects are stored differently than primitive types. Primitive types are stored directly in memory. Objects are stored elsewhere in a 7 memory and the associated variable pt contains a reference to that location. int a = 7; Point pt = new Point(9, 20); Point { 9 20 Memory
Java organizes groups of related classes into Packages To use Point, you need to know that it is in the "Abstract Windows Toolkit" package and put at the start of your program: import java. awt. *; public class Draw. Picture { public static void main(String[] args) { Point start = new Point(0, 0); Point finish = new Point(40, 20); int dist = start. distance(finish); . . . } }
When you copy a primitive type, it copies the value. When you copy an object, it copies the reference. The contents of the place in memory Memory are always copied. In one case it is a value and in the other is a reference. int a Point b Point = 7; pt 1 = new Point(9, 20); = a; pt 2 = pt 1; a pt 1 b pt 2 { Point 7 7 9 20
The same thing happens when you pass parameters to a method. When you pass a primitive type, it copies the value. When you pass an object, it copies the reference. int a = 7; Point pt 1 = new Point(9, 20); moo(a, pt 1); . . . public static int moo(int b, Point pt 2) {. . . Memory a pt 1 7 b pt 2 7 { Point 9 20
Activity: What does this code print? public static void main(String[] args) { int a = 7; Point pt 1 = new Point(10, 15); Point pt 2 = new Point(30, 40); pt 2 = mystery(a, pt 1); System. out. println("a= " + a); System. out. println(pt 1); System. out. println(pt 2); } public static Point mystery(int c, Point pt 3) { c += 3; a= 7 java. awt. Point[x=20, y=25] pt 3. translate(c, c); java. awt. Point[x=25, y=20] Point pt 4 = new Point(pt 3. y, pt 3. x); return pt 4; }
- Slides: 24