The this Reference The this reference, used inside a method, refers to the object through which the method is being executed Suppose the this reference.

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Chapter 4: Writing Classes
INF 523Q Chapter 4: Writing Classes (Examples). Coin.java b //****************************************************************** b // Coin.java Author:
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Computer Science II Recursion Professor: Evan Korth New York University.
Writing Classes in Java
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Chapter 6 Object-Oriented Design. 6-2 Program Development The creation of software involves four basic activities:  establishing the requirements  creating.
Java Review Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Classes, Encapsulation, Methods and Constructors
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Creating Classes. 2 Writing Classes Thus far, we have mainly used existing classes in the Java library  (also main classes for executing) True object-oriented.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley John Lewis, Peter DePasquale, and Joseph Chase Chapter 5: Writing Classes.
© 2004 Pearson Addison-Wesley. All rights reserved6-1 Chapter 6 : Object-Oriented Design Intermediate Java Programming Summer 2007.
Writing Classes (Chapter 4)
CSE 1301 Lecture 11 Object Oriented Programming Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
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.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 6 Object-Oriented Design Part 1. © 2004 Pearson Addison-Wesley. All rights reserved2/42 Object-Oriented Design Now we can extend our discussion.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Inheritance Reading for this Lecture: L&L 6.4 – 6.5.
© 2004 Pearson Addison-Wesley. All rights reserved November 7, 2007 Interfaces ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Object-Oriented Design Concepts
6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus.
6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
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.
Static class members.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
CSE 1201 Object Oriented Programming Object Oriented Design.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
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.
SEEM Java – Basic Introduction, Classes and Objects.
© 2004 Pearson Addison-Wesley. All rights reserved October 31, 2007 Static Class Members ComS 207: Programming I (in Java) Iowa State University, FALL.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
Outline Software Development Activities Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
1 Chapter 4: Writing Classes  Chapter 4 focuses on: class definitions encapsulation and Java modifiers method declaration, invocation, and parameter passing.
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 reserved November 2, 2007 Class Relationships ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
University of Turkish Aeronautical Association Computer Engineering Department CENG 112 COMPUTER PROGRAMMING 2 Tansel Dökeroglu, Ph.D.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Introduction to Recursion
Interfaces November 6, 2006 ComS 207: Programming I (in Java)
Introduction to Recursion
Passing Objects to Methods
More Object Oriented Programming
Chapter 5 – Writing Classes
Object Oriented Programming
Chapter 7 Object-Oriented 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.
Static Class Members March 29, 2006 ComS 207: Programming I (in Java)
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object Oriented Programming Review
Presentation transcript:

The this Reference The this reference, used inside a method, refers to the object through which the method is being executed Suppose the this reference is used inside a method called tryMe, which is invoked as follows: obj1.tryMe(); obj2.tryMe(); In the first invocation, the this reference refers to obj1 ; in the second it refers to obj2 Copyright © 2012 Pearson Education, Inc.

The this reference The this reference can be used to distinguish the instance variables of a class from corresponding method parameters with the same names Copyright © 2012 Pearson Education, Inc. public Account (String name, long acctNumber, double balance) { this.name = name; this.acctNumber = acctNumber; this.balance = balance; }

Dependency The following example defines a class called RationalNumber A rational number is a value that can be represented as the ratio of two integers Several methods of the RationalNumber class accept another RationalNumber object as a parameter See RationalTester.javaRationalTester.java See RationalNumber.javaRationalNumber.java Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // RationalTester.java Author: Lewis/Loftus // // Driver to exercise the use of multiple Rational objects. //******************************************************************** public class RationalTester { // // Creates some rational number objects and performs various // operations on them. // public static void main (String[] args) { RationalNumber r1 = new RationalNumber (6, 8); RationalNumber r2 = new RationalNumber (1, 3); RationalNumber r3, r4, r5, r6, r7; System.out.println ("First rational number: " + r1); System.out.println ("Second rational number: " + r2); continue

Copyright © 2012 Pearson Education, Inc. continue if (r1.isLike(r2)) System.out.println ("r1 and r2 are equal."); else System.out.println ("r1 and r2 are NOT equal."); r3 = r1.reciprocal(); System.out.println ("The reciprocal of r1 is: " + r3); r4 = r1.add(r2); r5 = r1.subtract(r2); r6 = r1.multiply(r2); r7 = r1.divide(r2); System.out.println ("r1 + r2: " + r4); System.out.println ("r1 - r2: " + r5); System.out.println ("r1 * r2: " + r6); System.out.println ("r1 / r2: " + r7); }

Copyright © 2012 Pearson Education, Inc. continue if (r1.isLike(r2)) System.out.println ("r1 and r2 are equal."); else System.out.println ("r1 and r2 are NOT equal."); r3 = r1.reciprocal(); System.out.println ("The reciprocal of r1 is: " + r3); r4 = r1.add(r2); r5 = r1.subtract(r2); r6 = r1.multiply(r2); r7 = r1.divide(r2); System.out.println ("r1 + r2: " + r4); System.out.println ("r1 - r2: " + r5); System.out.println ("r1 * r2: " + r6); System.out.println ("r1 / r2: " + r7); } Output First rational number: 3/4 Second rational number: 1/3 r1 and r2 are NOT equal. The reciprocal of r1 is: 4/3 r1 + r2: 13/12 r1 - r2: 5/12 r1 * r2: 1/4 r1 / r2: 9/4

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // RationalNumber.java Author: Lewis/Loftus // // Represents one rational number with a numerator and denominator. //******************************************************************** public class RationalNumber { private int numerator, denominator; // // Constructor: Sets up the rational number by ensuring a nonzero // denominator and making only the numerator signed. // public RationalNumber (int numer, int denom) { if (denom == 0) denom = 1; // Make the numerator "store" the sign if (denom < 0) { numer = numer * -1; denom = denom * -1; } continue

Copyright © 2012 Pearson Education, Inc. continue numerator = numer; denominator = denom; reduce(); } // // Returns the numerator of this rational number. // public int getNumerator () { return numerator; } // // Returns the denominator of this rational number. // public int getDenominator () { return denominator; } continue

Copyright © 2012 Pearson Education, Inc. continue // // Returns the reciprocal of this rational number. // public RationalNumber reciprocal () { return new RationalNumber (denominator, numerator); } // // Adds this rational number to the one passed as a parameter. // A common denominator is found by multiplying the individual // denominators. // public RationalNumber add (RationalNumber op2) { int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int sum = numerator1 + numerator2; return new RationalNumber (sum, commonDenominator); } continue

Copyright © 2012 Pearson Education, Inc. continue // // Subtracts the rational number passed as a parameter from this // rational number. // public RationalNumber subtract (RationalNumber op2) { int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int difference = numerator1 - numerator2; return new RationalNumber (difference, commonDenominator); } // // Multiplies this rational number by the one passed as a // parameter. // public RationalNumber multiply (RationalNumber op2) { int numer = numerator * op2.getNumerator(); int denom = denominator * op2.getDenominator(); return new RationalNumber (numer, denom); } continue

Copyright © 2012 Pearson Education, Inc. continue // // Divides this rational number by the one passed as a parameter // by multiplying by the reciprocal of the second rational. // public RationalNumber divide (RationalNumber op2) { return multiply (op2.reciprocal()); } // // Determines if this rational number is equal to the one passed // as a parameter. Assumes they are both reduced. // public boolean isLike (RationalNumber op2) { return ( numerator == op2.getNumerator() && denominator == op2.getDenominator() ); } continue

Copyright © 2012 Pearson Education, Inc. continue // // Returns this rational number as a string. // public String toString () { String result; if (numerator == 0) result = "0"; else if (denominator == 1) result = numerator + ""; else result = numerator + "/" + denominator; return result; } continue

Copyright © 2012 Pearson Education, Inc. continue // // Reduces this rational number by dividing both the numerator // and the denominator by their greatest common divisor. // private void reduce () { if (numerator != 0) { int common = gcd (Math.abs(numerator), denominator); numerator = numerator / common; denominator = denominator / common; } continue

Copyright © 2012 Pearson Education, Inc. continue // // Computes and returns the greatest common divisor of the two // positive parameters. Uses Euclid's algorithm. // private int gcd (int num1, int num2) { while (num1 != num2) if (num1 > num2) num1 = num1 - num2; else num2 = num2 - num1; return num1; }

Aggregation In the following example, a Student object is composed, in part, of Address objects A student has an address (in fact each student has two addresses) See Address.javaAddress.java See Student.javaStudent.java See StudentBody.javaStudentBody.java Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // StudentBody.java Author: Lewis/Loftus // // Demonstrates the use of an aggregate class. //******************************************************************** public class StudentBody { // // Creates some Address and Student objects and prints them. // public static void main (String[] args) { Address school = new Address ("800 Lancaster Ave.", "Villanova", "PA", 19085); Address jHome = new Address ("21 Jump Street", "Lynchburg", "VA", 24551); Student john = new Student ("John", "Smith", jHome, school); Address mHome = new Address ("123 Main Street", "Euclid", "OH", 44132); Student marsha = new Student ("Marsha", "Jones", mHome, school); System.out.println (john); System.out.println (); System.out.println (marsha); }

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // StudentBody.java Author: Lewis/Loftus // // Demonstrates the use of an aggregate class. //******************************************************************** public class StudentBody { // // Creates some Address and Student objects and prints them. // public static void main (String[] args) { Address school = new Address ("800 Lancaster Ave.", "Villanova", "PA", 19085); Address jHome = new Address ("21 Jump Street", "Lynchburg", "VA", 24551); Student john = new Student ("John", "Smith", jHome, school); Address mHome = new Address ("123 Main Street", "Euclid", "OH", 44132); Student marsha = new Student ("Marsha", "Jones", mHome, school); System.out.println (john); System.out.println (); System.out.println (marsha); } Output John Smith Home Address: 21 Jump Street Lynchburg, VA School Address: 800 Lancaster Ave. Villanova, PA Marsha Jones Home Address: 123 Main Street Euclid, OH School Address: 800 Lancaster Ave. Villanova, PA 19085

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // Student.java Author: Lewis/Loftus // // Represents a college student. //******************************************************************** public class Student { private String firstName, lastName; private Address homeAddress, schoolAddress; // // Constructor: Sets up this student with the specified values. // public Student (String first, String last, Address home, Address school) { firstName = first; lastName = last; homeAddress = home; schoolAddress = school; } continue

Copyright © 2012 Pearson Education, Inc. continue // // Returns a string description of this Student object. // public String toString() { String result; result = firstName + " " + lastName + "\n"; result += "Home Address:\n" + homeAddress + "\n"; result += "School Address:\n" + schoolAddress; return result; }

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // Address.java Author: Lewis/Loftus // // Represents a street address. //******************************************************************** public class Address { private String streetAddress, city, state; private long zipCode; // // Constructor: Sets up this address with the specified data. // public Address (String street, String town, String st, long zip) { streetAddress = street; city = town; state = st; zipCode = zip; } continue

Copyright © 2012 Pearson Education, Inc. continue // // Returns a description of this Address object. // public String toString() { String result; result = streetAddress + "\n"; result += city + ", " + state + " " + zipCode; return result; }

Examples See Client.java Client.java See Bus.java Bus.java See BusApp.java BusApp.java Copyright © 2012 Pearson Education, Inc.

Examples See Book.java Book.java See BookTest.java BookTest.java See Library.javaLibrary.java See TestLibrary.javaTestLibrary.java Copyright © 2012 Pearson Education, Inc.

Identifying Classes and Objects A partial requirements document: Of course, not all nouns will correspond to a class or object in the final solution The user must be allowed to specify each product by its primary characteristics, including its name and product number. If the bar code does not match the product, then an error should be generated to the message window and entered into the error log. The summary report of all transactions must be structured as specified in section 7.A. Copyright © 2012 Pearson Education, Inc.

Identifying Classes and Objects Sometimes it is challenging to decide whether something should be represented as a class For example, should an employee's address be represented as a set of instance variables or as an Address object The more you examine the problem and its details the more clear these issues become When a class becomes too complex, it often should be decomposed into multiple smaller classes to distribute the responsibilities Copyright © 2012 Pearson Education, Inc.

Identifying Classes and Objects Part of identifying the classes we need is the process of assigning responsibilities to each class Every activity that a program must accomplish must be represented by one or more methods in one or more classes We generally use verbs for the names of methods In early stages it is not necessary to determine every method of every class – begin with primary responsibilities and evolve the design Copyright © 2012 Pearson Education, Inc.

UML Diagrams UML stands for the Unified Modeling Language UML diagrams show relationships among classes and objects A UML class diagram consists of one or more classes, each with sections for the class name, attributes (data), and operations (methods) Lines between classes represent associations A dotted arrow shows that one class uses the other (calls its methods) Copyright © 2012 Pearson Education, Inc.

UML Class Diagrams A UML class diagram for the RollingDice program: RollingDice +main (args : String[]) : void Die -faceValue : int +roll() : int +setFaceValue (int value) : void +getFaceValue() : int +toString() : String

Static 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 is first referenced All objects instantiated from the class share its static variables Changing the value of a static variable in one object changes it for all others Copyright © 2012 Pearson Education, Inc.

Static Class Members The following example keeps track of how many Slogan objects have been created using a static variable, and makes that information available using a static method See SloganCounter.javaSloganCounter.java See Slogan.javaSlogan.java Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // SloganCounter.java Author: Lewis/Loftus // // Demonstrates the use of the static modifier. //******************************************************************** public class SloganCounter { // // Creates several Slogan objects and prints the number of // objects that were created. // 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); continue

Copyright © 2012 Pearson Education, Inc. continue 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()); }

Copyright © 2012 Pearson Education, Inc. continue 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()); } Output Remember the Alamo. Don't Worry. Be Happy. Live Free or Die. Talk is Cheap. Write Once, Run Anywhere. Slogans created: 5

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // Slogan.java Author: Lewis/Loftus // // Represents a single slogan string. //******************************************************************** public class Slogan { private String phrase; private static int count = 0; // // Constructor: Sets up the slogan and counts the number of // instances created. // public Slogan (String str) { phrase = str; count++; } continue

Copyright © 2012 Pearson Education, Inc. continue // // Returns this slogan as a string. // public String toString() { return phrase; } // // Returns the number of instances of this class that have been // created. // public static int getCount () { return count; }

Examples See Circle.javaCircle.java See TestCircle.java TestCircle.java Copyright © 2012 Pearson Education, Inc.

Recursion In computer science, some problems are more easily solved by using recursive methods.

World’s Simplest Recursion Program public class Recursion { public static void main (String args[]) { count(0); System.out.println(); } public static void count (int index) { System.out.print (index); if (index < 2) count(index+1); } This program simply counts from 0-2: 012 This is where the recursion occurs. You can see that the count() method calls itself.

39 First two rules of recursion Base case: You must always have some base case which can be solved without recursion Making Progress: For cases that are to be solved recursively, the recursive call must always be a case that makes progress toward the base case. From Data Structures and Algorithms by Mark Allen Weiss

Factorials Computing factorials are a classic problem for examining recursion. A factorial is defined as follows: n! = n * (n-1) * (n-2) …. * 1; For example: 1! = 1 2! = 2 * 1 = 2 3! = 3 * 2 * 1 = 6 4! = 4 * 3 * 2 * 1 = 24 5! = 5 * 4 * 3 * 2 * 1 = 120 If you study this table closely, you will start to see a pattern.

Seeing the Pattern Seeing the pattern in the factorial example is difficult at first. But, once you see the pattern, you can apply this pattern to create a recursive solution to the problem. Divide a problem up into: –What we know (call this the base case) –Making progress towards the base Each step resembles original problem The method launches a new copy of itself (recursion step) to make the progress.

Recursive Solution public class FindFactorialRecursive { public static void main (String args[]) { for (int i = 1; i < 10; i++) System.out.println ( i + "! = " + findFactorial(i)); } public static int findFactorial (int number) { if (( number == 1) || (number == 0)) return 1; else return (number * findFactorial (number-1)); } Base Case. Making progress

43 Recursion pros and cons All recursive solutions can be implemented without recursion. Recursion is "expensive". The expense of recursion lies in the fact that we have multiple activation frames and the fact that there is overhead involved with calling a method. If both of the above statements are true, why would we ever use recursion? In many cases, the extra "expense" of recursion is far outweighed by a simpler, clearer algorithm which leads to an implementation that is easier to code.

Recursive Solution public class FindFactorialRecursive { public static void main (String args[]) { for (int i = 1; i < 10; i++) System.out.println ( i + "! = " + findFactorial(i)); } public static int findFactorial (int number) { if (( number == 1) || (number == 0)) return 1; else return (number * findFactorial (number-1)); } Base Case. Making progress