Download presentation
Presentation is loading. Please wait.
1
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus Java Software Solutions is published by Addison-Wesley Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved. Instructors using the textbook may use and modify these slides for pedagogical purposes.
2
2 References b Recall from Chapter 2 that an object reference holds the memory address of an object b Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object ChessPiece bishop1 = new ChessPiece(); bishop1
3
References b Things you can do with a reference: Declare it : String st;Declare it : String st; Assign a new value to itAssign a new value to it –st = new String(“java”); –st = st2; –st = null; Interact with the object using “dot” operator : st.length()Interact with the object using “dot” operator : st.length() Check for equivalenceCheck for equivalence –(st == st2) –(st == null)
4
The null Reference b An object reference variable that does not currently point to an object is called a null reference The reserved word null can be used to explicitly set a null reference: name = null; or to check to see if a reference is currently null: if (name == null) System.out.println ("Invalid"); System.out.println ("Invalid");
5
The null Reference b An object reference variable declared at the class level (an instance variable) is automatically initialized to null b The programmer must carefully ensure that an object reference variable refers to a valid object before it is used Attempting to follow a null reference causes a NullPointerException to be thrown b Usually a compiler will check to see if a local variable is being used without being initialized
6
6 Assignment Revisited b The act of assignment takes a copy of a value and stores it in a variable b For primitive types: num2 = num1; Before num1 5 num2 12 After num1 5 num2 5
7
7 Reference Assignment b For object references, assignment copies the memory location: bishop2 = bishop1; Before bishop1bishop2 After bishop1bishop2
8
8 Aliases b Two or more references that refer to the same object are called aliases of each other b One object (and its data) can be accessed using different variables b Aliases can be useful, but should be managed carefully b Changing the object’s state (its variables) through one reference changes it for all of its aliases
9
9 Garbage Collection b When an object no longer has any valid references to it, it can no longer be accessed by the program b It is useless, and therefore called garbage b Java performs automatic garbage collection periodically, returning an object's memory to the system for future use b In other languages, the programmer has the responsibility for performing garbage collection
10
Passing Objects to Methods b Parameters in a Java method are passed by value b This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) b Passing parameters is essentially an assignment b When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other
11
Passing Objects to Methods b What you do to a parameter inside a method may or may not have a permanent effect (outside the method) b See ParameterPassing.java (page 226) ParameterPassing.java b See ParameterTester.java (page 228) ParameterTester.java b See Num.java (page 230) Num.java b Note the difference between changing the reference and changing the object that the reference points to
12
ParameterPAssing ParameterTester tester = new ParameterTester(); ParameterTester tester = new ParameterTester(); int a1 = 111; int a1 = 111; Num a2 = new Num (222); Num a2 = new Num (222); Num a3 = new Num (333); Num a3 = new Num (333); System.out.println ("Before calling changeValues:"); System.out.println ("Before calling changeValues:"); System.out.println ("a1\ta2\ta3"); System.out.println ("a1\ta2\ta3"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); tester.changeValues (a1, a2, a3); tester.changeValues (a1, a2, a3); System.out.println ("After calling changeValues:"); System.out.println ("After calling changeValues:"); System.out.println ("a1\ta2\ta3"); System.out.println ("a1\ta2\ta3"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n");
13
ParameterTester class ParameterTester { //----------------------------------------------------------------- //----------------------------------------------------------------- // Modifies the parameters, printing their values before and // Modifies the parameters, printing their values before and // after making the changes. // after making the changes. //----------------------------------------------------------------- //----------------------------------------------------------------- public void changeValues (int f1, Num f2, Num f3) public void changeValues (int f1, Num f2, Num f3) { System.out.println ("Before changing the values:"); System.out.println ("Before changing the values:"); System.out.println ("f1\tf2\tf3"); System.out.println ("f1\tf2\tf3"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); f1 = 999; f1 = 999; f2.setValue(888); f2.setValue(888); f3 = new Num (777); f3 = new Num (777); System.out.println ("After changing the values:"); System.out.println ("After changing the values:"); System.out.println ("f1\tf2\tf3"); System.out.println ("f1\tf2\tf3"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); }}
14
Num class Num { private int value; private int value; public Num (int update) { value = update; value = update; } public void setValue (int update) { value = update; value = update; } public String toString () { return value + ""; return value + ""; }}
15
Student Id Problem b Let’s suppose we have a Student class b How do we assign unique student id’s to each student object that we create? b What if we also want to get the latest Student created?
16
16 The static Modifier b In Chapter 2 we discussed static methods (also called class methods) that can be invoked through the class name rather than through a particular object For example, the methods of the Math class are static To make a method static, we apply the static modifier to the method definition The static modifier can be applied to variables as well b It associates a variable or method with the class rather than an object
17
17 Static Methods public static int triple (int num) { int result; result = num * 3; return result; } class Helper Because it is static, the method could be invoked as: value = Helper.triple (5);
18
18 Static Methods b The order of the modifiers can be interchanged, but by convention visibility modifiers come first Recall that the main method is static; it is invoked by the system without creating an object b Static methods cannot reference instance variables, because instance variables don't exist until an object exists b However, they can reference static variables or local variables
19
19 Static Variables b Static variables are sometimes called class variables b Normally, each object has its own data space b If a variable is declared as static, only one copy of the variable exists private static float price; b Memory space for a static variable is created as soon as the class in which it is declared is loaded
20
Static Variables b All objects created from the class share access to the static variable b Changing the value of a static variable in one object changes it for all others b Static methods and variables often work together b See CountInstances.java (page 233) CountInstances.java b See MyClass.java (page 234) MyClass.java
21
class MyClass { private static int count = 0; private static int count = 0; public MyClass () { public MyClass () { count++; count++; } public static int getCount () { public static int getCount () { return count; return count; }}------------------------- MyClass obj; MyClass obj; for (int scan=1; scan <= 10; scan++) for (int scan=1; scan <= 10; scan++) obj = new MyClass(); obj = new MyClass(); System.out.println ("Objects created: " + MyClass.getCount()); System.out.println ("Objects created: " + MyClass.getCount());
22
Student Example
23
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through which the method is being executed Suppose the this reference is used in a method called tryMe If tryMe is invoked as follows, the this reference refers to obj1 : obj1.tryMe(); But in this case, the this reference refers to obj2 : obj2.tryMe();
24
The this reference The this reference can also be used to distinguish the parameters of a constructor from the corresponding instance variables with the same names public Account (Sring name, long acctNumber, double balance) { this.name = name; this.acctNumber = acctNumber; this.balance = balance; }
25
Wrapper Classes b A wrapper class represents a particular primitive type b For example Integer ageObj = new Integer (20); uses the Integer class to create an object which effectively represents the integer 20 as an object b This is useful when a program requires an object instead of a primitive type
26
Wrapper Classes There is a wrapper class in the java.lang package for each primitive type: Primitive Type Wrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid
27
Wrapper Classes b Wrapper classes contain static methods that help manage the associated type For example, the Integer class contains a method to convert an integer stored in a String to an int value: num = Integer.parseInt (str); b The wrapper classes often contain useful static constants as well For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold the smallest and largest int values
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.