Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04a-JavaReview.ppt 1 94.204* Object-Oriented Software Development Unit.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
Advertisements

Programming and Data Structure
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
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.
Java Software Solutions
1 Objects, Classes, and Packages “Static” Classes Introduction to Classes Object Variables and Object References Instantiating Objects Using Methods in.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
Road Map Introduction to object oriented programming. Classes
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Games and Simulations O-O Programming in Java The Walker School
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CSE 501N Fall ‘09 04: Introduction to Objects 08 September 2009 Nick Leidenfrost.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
CSI 3125, Preliminaries, page 1 Class. CSI 3125, Preliminaries, page 2 Class The most important thing to understand about a class is that it defines a.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Learners Support Publications Constructors and Destructors.
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.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Constructors and Destructors
Chapter VII: Arrays.
Topic: Classes and Objects
User-Written Functions
Java Programming: Guided Learning with Early Objects
Intro To Classes Review
Chapter 3: Using Methods, Classes, and Objects
Road Map Introduction to object oriented programming. Classes
Java Review: Reference Types
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Classes, Encapsulation, Methods and Constructors (Continued)
Lecture 18 Arrays and Pointer Arithmetic
Constructors and Destructors
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Java Programming Language
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit 4(a) Java Review

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 2 Java Review In this unit, we shall briefly review the Java syntax that you are expected to know already : –Object Construction –Object References Aliasing.. As Method Parameters –Overloading –Arrays

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 3 Object Construction This statement declares variable c of class (type) Complex : Complex c; c is NOT a Complex object Instead, variable c can hold a reference to a Complex object

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 4 Object Construction Here’s how we create a Complex object:: c = new Complex(); new creates a new instance of class Complex The object initializes its state to its default value by invoking its default constructor new returns a reference to the object, which is assigned to c

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 5 Object Construction Often, we combine these two statements: Complex c = new Complex(); Important: students sometimes think that every time they declare a variable of class type, they must use this form (i.e., they think its illegal to declare a variable of class type without initializing it to refer to a new instance of the class) This is not true!

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 6 Object Construction The statement c = new Complex(5.2); creates a new Complex object that represents i The statement c = new Complex(-8.5, 9.1); creates a new Complex object that represents i

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 7 Object References Consider the declaration Complex c; c is NOT an object of class Complex c is a variable whose value is a reference to a Complex object (an instance of class Complex ) Aside: for brevity, we often use phrases like “object c” when we really mean “the object to which c refers”. This is o.k., as long as we remember that, in Java, all variables of class type store references to objects

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 8 Object References Suppose the declaration: Complex c; reserves a word of memory at address This word is initialized to the null reference, null –when the value of a variable of class type is null, it does not refer to any object c represents null

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 9 Object References Suppose new allocates a new object at address c = new Complex(); This address is returned by new and stored in c –N.B. a reference is not necessarily a 32- bit address, but to simplify explanations, we will assume it is

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 10 Object References c c now refers to the object real imag

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 11 Object References We’ll often use this notation when we want to distinguish between variables of class type and objects referred to by those variables Variable containing an object reference An object A reference to an object

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 12 Object References Example: variable c, after it has been assigned the reference to the new Complex object c

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 13 c3 = c1.plus(c2); i i c1 c2 Complex number c1: give me a new complex number that contains the sum of your value and the value of complex number c2

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 14 Aliasing Consider: Complex c = new Complex(); Complex c1; c1 = c; The = operator assigns the value of c (an object reference) to c1 c1 and c are now aliased to (i.e., they refer to) the same object

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 15 Aliasing Before c1 = c; is executed: c c1

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 16 Aliasing After c1 = c; is executed: c c1

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 17 Another Aliasing Example Complex c1 = new Complex(5.0, 3.0); Complex c2 = new Complex(-1.0, 2.0); c1 c

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 18 Another Aliasing Example The = operator does not copy objects c1 = c2; does NOT do this: c1 c

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 19 Another Aliasing Example After c1 = c2; is executed, c1 and c2 refer to the same object: c1 c

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 20 Another Aliasing Example What happens to the object that represents i? No variables refer to that object, so it can no longer receive messages The Java run-time system will garbage- collect the object (reclaim the memory allocated to the object for reuse)

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 21 Object References as Method Parameters Parameter c of plus() is declared as Complex public Complex plus(Complex c) { Complex sum = new Complex(real + c.real, imag + c.imag); return sum; }

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 22 Object References as Method Parameters The argument of the plus() message is a reference to a Complex object: Complex c1 = new Complex(5.1, -8.6); Complex c2 = new Complex(4.9); Complex c3; // c3 = c1 + c2 c3 = c1.plus(c2);

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 23 Object References as Method Parameters Some books say that Java passes objects by reference, other books say that it passes objects by value Which is it? When the plus() message is sent to the object referred to by c1: c3 = c1.plus(c2); the value stored in argument c2 is passed by value to formal parameter c Java ALWAYS passes arguments to methods by value

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 24 Object References as Method Parameters The value stored in c2 is a reference to an object Therefore, formal parameter c is aliased to the object referred to by c2 when the plus() method is invoked c2 c

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 25 Object References as Method Parameters In other words, when a method parameter has class type, the argument (a reference to an object) is passed by value to the parameter Because the value is a reference to an object, that’s why some books say that Java objects are passed by reference to methods

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 26 Tracing the Execution of plus() c3 = c1.plus(c2); After the plus() message is sent to c1, but before Complex sum = new Complex(...); is executed...

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 27 Tracing the Execution of plus() c2 c c1 c3

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 28 c2 c sum c1 c3 Tracing the Execution of plus() After Complex sum = new Complex(...); is executed...

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 29 Tracing the Execution of plus() After plus() returns, the object reference it returns is assigned to c3: c3 = c1.plus(c2); Variable sum and parameter c “disappear”

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 30 Tracing the Execution of plus() c2 c1 c3

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 31 A Note About Instance Variable Visibility Notice that plus() directly accesses the real and imag variables –of the Complex object that receives the message –of the Complex object referenced by parameter c Students sometimes think that a method can access the private variables of the object that received the message, but cannot access the private variables of other instances of the same class This is not true

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 32 A Note About Instance Variable Visibility A method defined in one class can access the private variables of any instance of the same class A method defined in one class cannot access the private variables of objects that are instances of other classes

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 33 Overloading Methods Overloading permits several methods to have the same name –They must be distinguished by different argument lists –Having only a different return type will not be sufficient - compile error When invoking an overloaded method, Java determines which method to invoke based on the method’s signature signature == the number of parameters in the method’s parameter list, and their types

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 34 Classes Can Have Several Constructors We have already seen that class Complex has 3 constructors: public Complex() {...} public Complex(double rp) {...} public Complex(double rp, double ip) {...} Complex x = new Complex(); –invokes the 0-argument (default) constructor Complex y = new Complex(-7.3); –invokes the 1-argument constructor Complex z = new Complex(1.2, 3.7); –invokes the 2-argument constructor

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 35 Overloading Complex ’s plus() method Overloading isn't limited to constructors - methods can be overloaded Suppose we want to be able to add a real number to a complex number We could create a new complex number from the real number (i.e., use the 1- argument constructor), then pass that complex number to plus() Instead, why not have a second plus() method, one that accepts a real number argument?

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 36 Overloading Complex ’s plus() method /** * Return the sum of this * Complex number and its * argument. * r A real number * to be added to this * complex number. A new Complex * number equal to the sum * this Complex number * and r. */

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 37 Overloading Complex ’s plus() method public Complex plus(double r) { // r is same as r + 0.0i Complex sum = new Complex( real + r, imag); return sum; } This plus() method and the one we saw earlier both have 1 parameter, but the types are different

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 38 Overloading Complex ’s plus() method Overloaded methods have the same method name but different signatures When a message is sent to an object, the Java interpreter checks the number & types of the arguments and the type of the return value, and looks for a method with a compatible signature –e.g., when the plus() message is sent to a Complex object Java determines which plus() method to invoke based on whether the argument is of type Complex or type double

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 39 Overloading Methods continued Overloading eliminates the need for multiple names for essentially the same function - error prone and tedious: int SquareInt (int val) { return val * val; } float SquareFloat (float val) { return val * val; }

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 40 Overloading Methods continued Multiple names are eliminated int Square (int val) { return val * val; } float Square (float val) { return val*val; } Different return types WILL NOT suffice int DoX() {…} float DoX {…} // Wrong

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 41 Java Arrays A Java array is a container which holds a contiguous collection of elements of the same type –An array is a special type of object - it has no class Handled directly by compiler Is a pseudo-primitive type There are 2 types of arrays –Array of primitive values –Array of references to objects Array of primitive Array of references to values objects Just like C/C++ they are indexed from primVal [0] primVal [1] primVal [n - 1]... ref [0] ref [1] ref [n - 1] obj0 obj1 obj

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 42 Arrays of Primitive Values An array must be declared and space must be allocated for it // Declare a reference to an array of integers int [] intArray; // No memory allocated yet! // Allocate space for 4 int elements intArray = new int [4]; // Note the [] intArray intArray [0] intArray [1] intArray [2] intArray [3] intArray

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 43 Arrays of Primitive Values continued intArray [0] = 25; intArray [1] = 43; intArray [2] = 57; intArray [3] = 79; We can declare and allocate space for the primitive values in one step int [] intArray = new int [4];... Declare, allocate and initialize in 1 step int [] intArray = {25, 43, 57, 79}; –Convenient - don't have to think about array length intArray [0] intArray [1] intArray [2] intArray [3] intArray

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 44 Arrays of Objects Arrays of objects require an additional step (to allocate memory for the objects) // First, declare a reference to an array of // references to PairClass objects (just like // declaring an array of primitive type) PairClass [] pairArray; // No mem allocated yet! // Allocate space for 4 references to PairClass objs pairArray = new PairClass [4]; pairArray [0] pairArray [1] pairArray [2] pairArray [3] pairArray Array of 4 uninitialized references to PairClass objects

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 45 Here's the Extra Step.. // Allocate space for the PairClass objects //..assume a PairClass (int x, int y) constructor.. pairArray [0] = new PairClass (5,9); // … Repeat for elements 1, 2 and 3… We can also declare and allocate space for the references to objects in 1 step PairClass [] pairArray = new PairClass [4];... Declare, allocate array of references and allocate space for objects in 1 step PairClass [] pairArray = { new PairClass (5,9), new PairClass (9,4) new PairClass (6,3), new PairClass (2,1) }; pairArray [0] pairArray [1] pairArray [2] pairArray [3] pairArray 5,9 PairClass obj 9,4 PairClass obj 6,3 PairClass obj 2,1 PairClass obj

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 46 Array length Instance Variable A useful public instance variable for array objects –length is the length of the array object pairArray.length is equal to 4 for ( int i = 0; i < pairArray.length; i++) { pairArray [i] = new PairClass (); pairArray [i].setA (0); pairArray [i].setB (i); } This is another example of encapsulation –The array object knows how big it is –We don't need to maintain some constant outside the array object that has to be passed to every method that operates on arrays of that type

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 47 length and final Variables The length instance variable is final –It can be assigned only once (i.e. when the array is instantiated) –This is true of all final variables final int someInt = 3; // Proper way... is the same as final int someInt; // Don't do this! someInt = 3; // Legal - but a bad idea! … // Now, attempt to reassign the value // The compiler will flag this as an error someInt = 4; // Compiler error See Ch for details about multi- dimensional arrays

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 48 Are You Ready ? In the next series of slides, poor code is presented. –For the Complex class already introduced, we want a method that will allow us to add two complex numbers and store the sum. If you can figure out the problems in the code by yourself, you are ready. If you can follow the discussion, prepare yourself for some work. If you can’t follow the discussion, you are not ready for

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 49 A Poor Version of plus() public void plus(Complex c, Complex sum) { sum.setReal(real + c.real); sum.setImag(imag + c.imag); } This version has two parameters –a reference to the object that is to be added to the object that receives the message –a reference to the object that will contain the sum

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 50 A Poor Version of plus() Code showing how to invoke the method: Complex c1 = new Complex(5.1, -8.6); Complex c2 = new Complex(4.9); Complex c3 = new Complex(); // c3 = c1 + c2 c1.plus(c2, c3); Explain how this code works. Identify the precondition that programmers must meet before invoking this method.

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 51 A Poor Version of plus() Notice that the client must instantiate the Complex object (referred to by c3 ) where the result will be stored, before sum is aliased to the same object as c3 Sending the setReal() and setImag() messages to sum changes the state of the object referred to by c3 This is not obvious from the statement that sends the plus() message to c1

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 52 Side Effects If a method changes the state of an object that is passed to it as an argument (e.g., by sending the object a setter message), this is known as a side-effect of the method invocation This must be well-documented near the code that invokes the method In general, it is better for a method to create a new object and return a reference to it (instead of changing the state of the objects passed as method arguments)

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 53 Why Doesn’t This Code Work? This version of plus() creates the object that holds the result: public void plus( Complex c, Complex sum) { sum = new Complex (real + c.real, imag+ c.imag); }

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 54 Why Doesn’t This Code Work? Complex c1 = new Complex(5.1, -8.6); Complex c2 = new Complex(4.9); Complex c3; // c3 = c1 + c2 c1.plus(c2, c3); So why doesn’t c3 have the correct result when plus() returns? (Hint: trace the execution using box-oval diagrams)

Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt 55 The Good Version public Complex plus(Complex c) { Complex sum = new Complex( real + c.real, imag + c.imag ); return sum; } Complex c1 = new Complex( 5.1, -8.6); Complex c2 = new Complex( 4.9 ); Complex c3; // c3 = c1 + c2 C3 = c1.plus( c2 ); Explain why this version is “good code”.