Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li.

Similar presentations


Presentation on theme: "CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li."— Presentation transcript:

1 CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li

2 Review: The String class Console output/input – System.out.print – System.out.println – System.out.printf – The Scanner class Flow of control – Branching – looping

3 Ten Important Questions about Classes in java: 1. What are the contents of a class? 2. Where are they placed within a class? 3. What are instance variables and local variables? 4. What is the difference between primitive type values and class type values? 5. Which operator do you need to create an object? 6. What is the meaning of the reserved word “this”? 7. When do you use the modifier public or private? 8. What is a constructor? How many constructors can a class have? 9. What are static methods and static variables? 10. What are reference variables and value variables?

4 Defining Classes: The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects will have – These data items and methods are sometimes called members of the object – Data items are called fields or instance variables Where can instance variable declarations and method definitions be placed within the class definition – Anywhere and in any order Local variables vs. instance variables 4-4 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

5 Primitive Type Values vs. Class Type Values A primitive type value is a single piece of data A class type value or object can have multiple pieces of data, as well as actions called methods – All objects of a class have the same methods – All objects of a class have the same pieces of data (i.e., name, type, and number) – For a given object, each piece of data can hold a different value 4-5 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

6 The new Operator An object of a class is named or declared by a variable of the class type: ClassName classVar; The new operator must then be used to create the object and associate it with its variable name: classVar = new ClassName(); These can be combined as follows: ClassName classVar = new ClassName(); 4-6 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

7 Instance Variables and Methods Instance variables can be defined as in the following two examples – Note the public modifier (for now): public String instanceVar1; public int instanceVar2; In order to refer to a particular instance variable, preface it with its object name as follows: objectName.instanceVar1 objectName.instanceVar2 4-7 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

8 The this Parameter All instance variables are understood to have. in front of them If an explicit name for the calling object is needed, the keyword this can be used – myInstanceVariable always means and is always interchangeable with this.myInstanceVariable 4-8 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

9 The methods equals and toString Java expects certain methods, such as equals and toString, to be in all, or almost all, classes The purpose of equals, a boolean valued method, is to compare two objects of the class to see if they satisfy the notion of "being equal" – Note: You cannot use == to compare objects public boolean equals(ClassName objectName) The purpose of the toString method is to return a String value that represents the data in the object public String toString() 4-9 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

10 public and private Modifiers The modifier public means that there are no restrictions on where an instance variable or method can be used The modifier private means that an instance variable or method cannot be accessed by name outside of the class It is considered good programming practice to make all instance variables private Most methods are public, and thus provide controlled access to the object Usually, methods are private only if used as helping methods for other methods in the class 4-10 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

11 A Class Has Access to Private Members of All Objects of the Class Within the definition of a class, private members of any object of the class can be accessed, not just private members of the calling object 4-11 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

12 Overloading Overloading is when two or more methods in the same class have the same method name To be valid, any two definitions of the method name must have different signatures – A signature consists of the name of a method together with its parameter list – Differing signatures must have different numbers and/or types of parameters 4-12 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

13 Overloading and Automatic Type Conversion If Java cannot find a method signature that exactly matches a method invocation, it will try to use automatic type conversion The interaction of overloading and automatic type conversion can have unintended results In some cases of overloading, because of automatic type conversion, a single method invocation can be resolved in multiple ways – Ambiguous method invocations will produce an error in Java 4-13 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

14 Constructors A constructor is a special kind of method that is designed to initialize the instance variables for an object: public ClassName(anyParameters){code} – A constructor must have the same name as the class – A constructor has no type returned, not even void – Constructors are typically overloaded 4-14 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

15 Constructors A constructor is called when an object of the class is created using new ClassName objectName = new ClassName(anyArgs); – The name of the constructor and its parenthesized list of arguments (if any) must follow the new operator – This is the only valid way to invoke a constructor: a constructor cannot be invoked like an ordinary method If a constructor is invoked again (using new ), the first object is discarded and an entirely new object is created – If you need to change the values of instance variables of the object, use mutator methods instead 4-15 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

16 You Can Invoke Another Method in a Constructor The first action taken by a constructor is to create an object with instance variables Therefore, it is legal to invoke another method within the definition of a constructor, since it has the newly created object as its calling object – For example, mutator methods can be used to set the values of the instance variables – It is even possible for one constructor to invoke another 4-16 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

17 A Constructor Has a this Parameter Like any ordinary method, every constructor has a this parameter The this parameter can be used explicitly, but is more often understood to be there than written down The first action taken by a constructor is to automatically create an object with instance variables Then within the definition of a constructor, the this parameter refers to the object created by the constructor 4-17 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

18 Include a No-Argument Constructor If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created If you include even one constructor in your class, Java will not provide this default constructor If you include any constructors in your class, be sure to provide your own no-argument constructor as well 4-18 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

19 Static Methods A static method is one that can be used without a calling object A static method still belongs to a class, and its definition is given inside the class definition When a static method is defined, the keyword static is placed in the method header public static returnedType myMethod(parameters) {... } Static methods are invoked using the class name in place of a calling object returnedValue = MyClass.myMethod(arguments); 5-19 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

20 Static Variables A static variable is a variable that belongs to the class as a whole, and not just to one object – There is only one copy of a static variable per class, unlike instance variables where each object has its own copy All objects of the class can read and change a static variable Although a static method cannot access an instance variable, a static method can access a static variable A static variable is declared like an instance variable, with the addition of the modifier static private static int myStaticVariable; 5-20 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

21 Static Variables A static variable should always be defined private, unless it is also a defined constant – The value of a static defined constant cannot be altered, therefore it is safe to make it public – In addition to static, the declaration for a static defined constant must include the modifier final, which indicates that its value cannot be changed public static final int BIRTH_YEAR = 1954; When referring to such a defined constant outside its class, use the name of its class in place of a calling object int year = MyClass.BIRTH_YEAR; 5-21 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

22 Variables and Memory A computer has two forms of memory Secondary memory is used to hold files for "permanent" storage Main memory is used by a computer when it is running a program – Values stored in a program's variables are kept in main memory 5-22 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

23 Variables and Memory Main memory consists of a long list of numbered locations called bytes – Each byte contains eight bits: eight 0 or 1 digits The number that identifies a byte is called its address – A data item can be stored in one (or more) of these bytes – The address of the byte is used to find the data item when needed 5-23 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

24 Variables and Memory Values of most data types require more than one byte of storage – Several adjacent bytes are then used to hold the data item – The entire chunk of memory that holds the data is called its memory location – The address of the first byte of this memory location is used as the address for the data item A computer's main memory can be thought of as a long list of memory locations of varying sizes 5-24 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

25 Variables in Memory 5-25 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

26 References Every variable is implemented as a location in computer memory When the variable is a primitive type, the value of the variable is stored in the memory location assigned to the variable – Each primitive type always require the same amount of memory to store its values 5-26 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

27 References When the variable is a class type, only the memory address (or reference) where its object is located is stored in the memory location assigned to the variable – The object named by the variable is stored in some other location in memory – Like primitives, the value of a class variable is a fixed size – Unlike primitives, the value of a class variable is a memory address or reference – The object, whose address is stored in the variable, can be of any size 5-27 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

28 References Two reference variables can contain the same reference, and therefore name the same object – The assignment operator sets the reference (memory address) of one class type variable equal to that of another – Any change to the object named by one of theses variables will produce a change to the object named by the other variable, since they are the same object variable2 = variable1; 5-28 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

29 Class Type Variables Store a Reference (Part 1 of 2) 5-29 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

30 Class Type Variables Store a Reference (Part 2 of 2) 5-30 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

31 Assignment Operator with Class Type Variables (Part 1 of 3) 5-31 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

32 Assignment Operator with Class Type Variables (Part 2 of 3) 5-32 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

33 Assignment Operator with Class Type Variables (Part 3 of 3) 5-33 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

34 Class Parameters All parameters in Java are call-by-value parameters – A parameter is a local variable that is set equal to the value of its argument – Therefore, any change to the value of the parameter cannot change the value of its argument Class type parameters appear to behave differently from primitive type parameters – They appear to behave in a way similar to parameters in languages that have the call-by-reference parameter passing mechanism 5-34 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

35 Class Parameters The value plugged into a class type parameter is a reference (memory address) – Therefore, the parameter becomes another name for the argument – Any change made to the object named by the parameter (i.e., changes made to the values of its instance variables) will be made to the object named by the argument, because they are the same object – Note that, because it still is a call-by-value parameter, any change made to the class type parameter itself (i.e., its address) will not change its argument (the reference or memory address) 5-35 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

36 Parameters of a Class Type 5-36 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

37 Public static void changer(ToyClass aparameter) { aParameter.name =“Hot Shot”; aParameter.number = 42; } The changer method in ToyClass

38 Memory Picture for Display 5.14 (Part 1 of 3) 5-38 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

39 Memory Picture for Display 5.14 (Part 2 of 3) 5-39 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

40 Memory Picture for Display 5.14 (Part 3 of 3) 5-40 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

41 Differences Between Primitive and Class-Type Parameters A method cannot change the value of a variable of a primitive type that is an argument to the method In contrast, a method can change the values of the instance variables of a class type that is an argument to the method 5-41 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

42 Comparing Parameters of a Class Type and a Primitive Type (Part 1 of 2) 5-42 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

43 Comparing Parameters of a Class Type and a Primitive Type (Part 2 of 2) 5-43 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

44 A Toy Class to Use in Display 5.16 (Part 1 of 2) 5-44 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

45 A Toy Class to Use in Display 5.16 (Part 2 of 2) 5-45 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

46 Copy Constructors A copy constructor is a constructor with a single argument of the same type as the class The copy constructor should create an object that is a separate, independent object, but with the instance variables set so that it is an exact copy of the argument object Note how, in the Date copy constructor, the values of all of the primitive type private instance variables are merely copied 5-46 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

47 Copy Constructor for a Class with Primitive Type Instance Variables public Date(Date aDate) { if (aDate == null) //Not a real date. { System.out.println("Fatal Error."); System.exit(0); } month = aDate.month; day = aDate.day; year = aDate.year; } 5-47 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

48 Copy Constructor for a Class with Class Type Instance Variables Unlike the Date class, the Person class contains three class type instance variables If the born and died class type instance variables for the new Person object were merely copied, then they would simply rename the born and died variables from the original Person object born = original.born //dangerous died = original.died //dangerous – This would not create an independent copy of the original object 5-48 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

49 Mutable and Immutable Classes A class that contains no methods (other than constructors) that change any of the data in an object of the class is called an immutable class – Objects of such a class are called immutable objects – It is perfectly safe to return a reference to an immutable object because the object cannot be changed in any way – The String class is an immutable class 5-49 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

50 Mutable and Immutable Classes A class that contains public mutator methods or other public methods that can change the data in its objects is called a mutable class, and its objects are called mutable objects – Never write a method that returns a mutable object – Instead, use a copy constructor to return a reference to a completely independent copy of the mutable object 5-50 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

51 Deep Copy Versus Shallow Copy A deep copy of an object is a copy that, with one exception, has no references in common with the original – Exception: References to immutable objects are allowed to be shared Any copy that is not a deep copy is called a shallow copy – This type of copy can cause dangerous privacy leaks in a program 5-51 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

52 Exercise: What is the output of the following code? Date date1 = new Date(“January”,1,2006); Date date2; date2 = date1; System.out.println(date2); date2.setDate(“July”,4, 1776); System.out.println(date1); System.out.println(date2); Date date1 = new Date(“January”,1,2006); Date date2; date2 = new Date(date1); System.out.println(date2); date2.setDate(“July”,4, 1776); System.out.println(date1); System.out.println(date2); Code A Code B

53 The StringTokenizer Class The StringTokenizer class is used to recover the words or tokens in a multi-word String – You can use whitespace characters to separate each token, or you can specify the characters you wish to use as separators – In order to use the StringTokenizer class, be sure to include the following at the start of the file: import java.util.StringTokenizer; 4-53 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

54 Some Methods in the StringTokenizer Class (Part 1 of 2) 4-54 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

55 Some Methods in the StringTokenizer Class (Part 2 of 2) 4-55 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

56 The Math Class http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html The Math class provides a number of standard mathematical methods – It is found in the java.lang package, so it does not require an import statement – All of its methods and data are static, therefore they are invoked with the class name Math instead of a calling object – The Math class has two predefined constants, E ( e, the base of the natural logarithm system) and PI ( , 3.1415...) area = Math.PI * radius * radius; 5-56 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

57 Some Methods in the Class Math (Part 1 of 5) 5-57 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

58 Some Methods in the Class Math (Part 2 of 5) 5-58 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

59 Some Methods in the Class Math (Part 3 of 5) 5-59 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

60 Some Methods in the Class Math (Part 4 of 5) 5-60 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

61 Some Methods in the Class Math (Part 5 of 5) 5-61 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

62 Announcement: Programming assignment 1: – Page 92: project 9. Page 160: project 3. Due date: – Thursday, Feb 14th. Late work may be submitted on Friday or Saturday with 5% penalty per day. No work will be accepted after Saturday. How to turn in: – Email your files (both.java &.class files) to TA and me with “cs102 assignment1” in your message subject line. Grading. – Correctness: 80 points. – Readability: 20 points.


Download ppt "CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li."

Similar presentations


Ads by Google