1 Enhancing Classes  Now we can explore various aspects of classes and objects in more detail  Chapter 5 focuses on: object references and aliases passing.

Slides:



Advertisements
Similar presentations
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
Java Software Solutions
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Chapter 5: Enhancing Classes
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Chapter 5: Keyboard I/O & Simple GUI’s Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
Primitive Types vs. Reference Types Variables of primitive types hold the values of the primitive types directly. Variables of reference types hold references.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Enhancing classes Visibility modifiers and encapsulation revisited
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Classes, Encapsulation, Methods and Constructors
INF 523Q Chapter 5: Enhancing Classes (Examples).
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
Reference … and Misc Other Topics Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Static Class Members Wrapper Classes Autoboxing Unboxing.
INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley John Lewis, Peter DePasquale, and Joseph Chase Chapter 5: Writing Classes.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSE 1301 Lecture 11 Object Oriented Programming Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
6-1 Object-Oriented Design Today we focuses on: –the this reference (Chapter 7) –the static modifier (Chapter 7) –method overloading (Chapter 7)
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
Chapter 5: Enhancing Classes
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 7 Object-Oriented Design Concepts
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Programming in Java (COP 2250) Lecture 8 Chengyong Yang Fall, 2005.
Using Classes and Objects. We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: Object creation.
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
CSE 1201 Object Oriented Programming Using Classes and Objects.
1 Object-Oriented Design Now we can extend our discussion of the design of classes and objects Chapter 6 focuses on: software development activities determining.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
SEEM Java – Basic Introduction, Classes and Objects.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
3-1 Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as a type to declare an object reference.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
© 2004 Pearson Addison-Wesley. All rights reserved November 12, 2007 Inheritance ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
© 2004 Pearson Addison-Wesley. All rights reserved January 27, 2006 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Chapter 5: Enhancing Classes
Variables in Java A variable holds either
Chapter 7 User-Defined Methods.
Formatting Output & Enumerated Types & Wrapper Classes
Chapter 5: Enhancing Classes
More Object Oriented Programming
Object Oriented Programming
CSI 1102 Introduction to Software Design
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.
Chapter 5: Enhancing Classes
Static is one of the modifiers that determine variable and method characteristics. The static modifier associates a variable or method with its class.
Java Classes Aliases & Null & This
Object Oriented Programming Review
Outline Creating Objects The String Class The Random and Math Classes
Object-Oriented Design Part 2
Presentation transcript:

1 Enhancing Classes  Now we can explore various aspects of classes and objects in more detail  Chapter 5 focuses on: object references and aliases passing objects references as parameters the static modifier wrapper classes nested classes and inner classes

2 References  Recall from Chapter 2 that an object reference variable holds the memory address of an object  Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object ChessPiece bishop1 = new ChessPiece(); bishop1

The null Reference  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");

The null Reference  An object reference variable declared at the class level (an instance variable) is automatically initialized to null  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  Usually a compiler will check to see if a local variable is being used without being initialized

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

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; }

7 Assignment Revisited  The act of assignment takes a copy of a value and stores it in a variable  For primitive types: num2 = num1; Before num1 5 num2 12 After num1 5 num2 5

8 Reference Assignment  For object references, assignment copies the memory location: bishop2 = bishop1; Before bishop1bishop2 After bishop1bishop2

9 Aliases  Two or more references that refer to the same object are called aliases of each other  One object (and its data) can be accessed using different reference variables  Aliases can be useful, but should be managed carefully  Changing the object’s state (its variables) through one reference changes it for all of its aliases

Testing Objects for Equality  The == operator compares object references for equality, returning true if the references are aliases of each other bishop1 == bishop2  A method called equals is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator bishop1.equals(bishop2)  We can redefine the equals method to return true under whatever conditions we think are appropriate

11 Garbage Collection  When an object no longer has any valid references to it, it can no longer be accessed by the program  The object is useless, and therefore is called garbage  Java performs automatic garbage collection periodically, returning an object's memory to the system for future use  In other languages, the programmer is responsible for performing garbage collection

Objects as Parameters  Parameters in a Java method are passed by value  This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header)  Passing parameters is therefore similar to an assignment statement  When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other

Passing Objects to Methods  What you do with a parameter inside a method may or may not have a permanent effect (outside the method)  See ParameterPassing.java (page 277)ParameterPassing.java  See ParameterTester.java (page 279)ParameterTester.java  See Num.java (page 280)Num.java  Note the difference between changing the reference and changing the object that the reference points to

ParameterPassing.java ParameterPassing.java public class ParameterPassing { public static void main (String[] args) { ParameterTester tester = new ParameterTester(); int a1 = 111; Num a2 = new Num (222); Num a3 = new Num (333); System.out.println ("Before calling changeValues:"); System.out.println ("a1\ta2\ta3"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); tester.changeValues (a1, a2, a3); System.out.println ("After calling changeValues:"); System.out.println ("a1\ta2\ta3"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); }}

ParameterTester.java public class ParameterTester { public void changeValues (int f1, Num f2, Num f3) { System.out.println ("Before changing the values:"); System.out.println ("f1\tf2\tf3"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); f1 = 999; f2.setValue(888); f3 = new Num (777); System.out.println ("After changing the values:"); System.out.println ("f1\tf2\tf3"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); }}

Num.java Num.java public class Num { private int value; // Sets up the new Num object, storing an initial value. public Num (int update) { value = update; } // Sets the stored value to the newly specified value. public void setValue (int update) { value = update; } // Returns the stored integer value as a string. public String toString () { return value + ""; }}

17 The static Modifier  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: Math.sqrt (25)  To write a static method, we apply the static modifier to the method definition  The static modifier can be applied to variables as well  It associates a variable or method with the class rather than with an object

18 Static Variables  Static variables are also called class variables  Normally, each object has its own data space, but if a variable is declared as static, only one copy of the variable exists private static float price;  Memory space for a static variable is created when the class in which it is declared is loaded  All objects created from the class share static variables  Changing the value of a static variable in one object changes it for all others

19 Static Methods public static int triple (int num) { int result; result = num * 3; return result; } class Helper Because it is static, the method can be invoked as: value = Helper.triple (5);

20 Static Methods  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  Static methods cannot reference instance variables, because instance variables don't exist until an object exists  However, a static method can reference static variables or local variables

The static Modifier  Static methods and static variables often work together  See CountInstances.java (page 284)CountInstances.java  See Slogan.java (page 285)Slogan.java

CountInstances.java CountInstances.java public class CountInstances { public static void main (String[] args) { Slogan obj; obj = new Slogan ("Remember the Alamo."); System.out.println (obj); obj = new Slogan ("Don't Worry. Be Happy."); System.out.println (obj); obj = new Slogan ("Live Free or Die."); System.out.println (obj); obj = new Slogan ("Talk is Cheap."); System.out.println (obj); obj = new Slogan ("Write Once, Run Anywhere."); System.out.println (obj); System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); }}

Slogan.java public class Slogan{ private String phrase; private static int count = 0; public Slogan (String str) { phrase = str; count++; } public String toString() { return phrase; } public static int getCount () { return count; }}

Wrapper Classes  A wrapper class represents a particular primitive type  For example Integer ageObj = new Integer (20); uses the Integer class to create an object which effectively represents the integer 20 as an object  This is useful when a program requires an object instead of a primitive type

Wrapper Classes  There is a wrapper class in the java.lang package for each primitive type: Primitive TypeWrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid

Wrapper Classes  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);  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

Keyboard Input Revisited  The Keyboard class was introduced in Chapter 2 to facilitate capturing input from the keyboard  Recall that the Keyboard class was written by the authors of the book  The Keyboard class hides various aspects of Java input processing  But it is important to understand how that processing works

Reading Keyboard Input  Java I/O is accomplished using objects that represent streams of data  A stream is an ordered sequence of bytes  The System.out object represents a standard output stream, which defaults to the monitor screen  Reading keyboard input is more complicated  The input stream is made up of multiple objects: BufferedReader in = new BufferedReader ( new InputStreamReader (System.in));

Reading Keyboard Input  The System.in object is used to create an InputStreamReader object  The InputStreamReader object is used to create a BufferedReader object  This creates an input stream that treats input as characters and buffers them so that input can be read a line at a time  The readLine method of the BufferedReader class reads an entire line of input as a String  Wrapper class methods can be used to convert numeric input

Reading Keyboard Input  Problems that arise in reading or converting a value manifest themselves as exceptions  The throws clause of a method header indicates what exceptions it may throw  See Wages2.java (page 289)Wages2.java  I/O and exceptions are explored further in Chapter 8

Wages2.java import java.io.*; import java.text.NumberFormat; public class Wages2 { public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); String name; int hours; double rate, pay; System.out.print ("Enter your name: "); name = in.readLine (); System.out.print ("Enter the number of hours worked: "); hours = Integer.parseInt (in.readLine()); System.out.print ("Enter pay rate per hour: "); rate = Double.parseDouble (in.readLine()); System.out.println (); pay = hours * rate; NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println (name + ", your pay is: " + fmt.format(pay)); }}

Nested Classes  In addition to containing data and methods, a class can contain other classes  A class declared within another class is called a nested class Enclosing Class Nested Class

Nested Classes  A nested class has access to the variables and methods of the enclosing class, even if they are declared private  In certain situations this makes the implementation of the classes easier because they can share information easily  Furthermore, the nested class can be protected by the enclosing class from external use  This is a special relationship and should be used with care

Nested Classes  A nested class produces a separate bytecode file  If a nested class called Inside is declared in an outer class called Outside, two bytecode files are produced: Outside.class Outside$Inside.class  Nested classes can be declared as static, in which case they cannot refer to instance variables or methods

Inner Classes  A nonstatic nested class is called an inner class  An inner class is associated with each instance of the enclosing class  An instance of an inner class can exist only within an instance of an enclosing class  See TestInner.java (page 291)TestInner.java  See Outer.java (page 292)Outer.java

TestInner.java public class TestInner { public static void main (String[] args) { Outer out = new Outer(); System.out.println (out); System.out.println(); out.changeMessages(); System.out.println (out); }}

Outer.java public class Outer { private int num; private Inner in1, in2; public Outer() {num = 9876; in1 = new Inner ("Half of the problem is 90% mental."); in2 = new Inner ("Another deadline. Another miracle."); } public void changeMessages() { in1.message = "Life is uncertain. Eat dessert first."; in2.message = "One seventh of your life is spent on Mondays."; } public String toString() { return in1 + "\n" + in2; } private class Inner { public String message; public Inner (String str) { message = str; } public String toString() { num++; return message + "\nOuter num = " + num; }}}

Summary  Chapter 5 has focused on: object references and aliases passing objects references as parameters the static modifier wrapper classes nested classes and inner classes