Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by.

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

1
Final and Abstract Classes
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
Properties Use, share, or modify this drill on mathematic properties. There is too much material for a single class, so you’ll have to select for your.
David Burdett May 11, 2004 Package Binding for WS CDL.
Writing Pseudocode And Making a Flow Chart A Number Guessing Game
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
1 RA I Sub-Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Casablanca, Morocco, 20 – 22 December 2005 Status of observing programmes in RA I.
Conversion Problems 3.3.
4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.
DONT PANIC!! Lots of new notions coming in these slides Dont worry if not all of it makes perfect sense Well meet most of this stuff again in detail later.
1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure Definitions 10.3Initializing Structures 10.4Accessing.
Turing Machines.
PP Test Review Sections 6-1 to 6-6
Chapter 17 Linked Lists.
1 Linked Lists III Template Chapter 3. 2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
Semantic Analysis and Symbol Tables
EIS Bridge Tool and Staging Tables September 1, 2009 Instructor: Way Poteat Slide: 1.
2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Understanding class definitions Looking inside classes 5.0.
21-Aug-14 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
1 RA III - Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Buenos Aires, Argentina, 25 – 27 October 2006 Status of observing programmes in RA.
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
CONTROL VISION Set-up. Step 1 Step 2 Step 3 Step 5 Step 4.
1 User-Defined Classes The String class is a pre-defined class that is provided by the Java Designer. Sometimes programmers would like to create their.
While Loop Lesson CS1313 Spring while Loop Outline 1.while Loop Outline 2.while Loop Example #1 3.while Loop Example #2 4.while Loop Example #3.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
1 Variables and Data Types. 2 Variable Definition a location in memory, referenced by a name (identifier), where data of a given type can be stored, changed,
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
Chapter Three Arithmetic Expressions and Assignment Statements
Analyzing Genes and Genomes
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
Pointers and Arrays Chapter 12
Essential Cell Biology
PSSA Preparation.
Essential Cell Biology
Immunobiology: The Immune System in Health & Disease Sixth Edition
Energy Generation in Mitochondria and Chlorplasts
Murach’s OS/390 and z/OS JCLChapter 16, Slide 1 © 2002, Mike Murach & Associates, Inc.
User Defined Functions Lesson 1 CS1313 Fall User Defined Functions 1 Outline 1.User Defined Functions 1 Outline 2.Standard Library Not Enough #1.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four: Defining Your Own Classes *Instantiable.
Chapter Four Defining Your Own Classes continued.
Programming Languages and Paradigms Object-Oriented Programming.
Local Variables A local variable is a variable that is declared within a method declaration. Local variables are accessible only from the method in which.
Classes CS 21a: Introduction to Computing I First Semester,
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
Methods and Parameters. Slide 2 Internal “Convenience” Methods External Methods ways to respond to requests from external “users” e.g., deposit( int ),
Chapter 4 Defining Instantiable Classes
Defining Your Own Classes
Introduction to Object-Oriented Programming with Java--Wu
Classes CS 21a: Introduction to Computing I
Presentation transcript:

Objects & Methods Defining Classes

Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by default Need to call new to create a new object Different variables can point to same object at the same time

Slide 3 Reference Variables Revisited Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox) xyz (null) BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z;

Slide 4 Reference Variables Revisited xyz (null) BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox)

Slide 5 Reference Variables Revisited xyz (null) BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox)

Slide 6 Reference Variables Revisited xyz BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox)

Slide 7 Reference Variables Revisited BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; xyz Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox)

Slide 8 Reference Variables Revisited BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; xyz Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox)

Slide 9 Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox) Reference Variables Revisited BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; xyz

Slide 10 Something to think about Suppose int a; a = ; int b = a; a = a ; int c = b; … BankAccount x = new BankAccount(); x.deposit( ); BankAccount y = x; x.deposit( ); int z = y.getBalance(); What is the final value of c? z? Why? Answer: c is , while z is Why? Because a primitive-type variable copies the actual value, while object-type variables copies the reference b is independent from a on the other hand, y and x refer to the same BankAccount instance. (It’s a joint account!)

Objects (Part 2) Defining Classes

Slide 12 Using BankAccount objects BankAccount aliceAccount = new BankAccount(); BankAccount bobAccount = new BankAccount(); BankAccount chuckAccount = new BankAccount(); aliceAccount.deposit( 250 ); bobAccount.deposit( 100 ); int x = chuckAccount.getBalance(); Note: all BankAccount instances have the same structure int balance field int getBalance(), deposit(int), and withdraw(int) methods But each BankAccount instance has a distinct identity each instance has its own values for fields (e.g., balance) methods work on an instance’s own balance aliceAccount.deposit( 250 ) changes only aliceAccount’s balance, not bobAccount’s

Slide 13 Classes A Class describes the general structure of objects belonging to that class fields/attributes (state) methods (behavior) e.g., The BankAccount class says that: all BankAccount objects have its own balance field of type int all BankAccount objects have a deposit method which increments the object’s own balance field A Class is like a “recipe” or “template”

Slide 14 Defining Classes public class BankAccount { private int balance; // current amount public BankAccount() { // does nothing. defaults to balance=0 } public int getBalance() { return balance; } public void deposit( int amount ) { balance += amount; } Class name (must be same as file name) Fields Constructors Methods

Slide 15 Methods Applets are Objects too! public class BankApplet1 extends IOApplet { BankAccount account; public void setup() { account = new BankAccount(); addInput( "Amount" ); addButton( "Deposit" ); addOutput(); println( "Balance is P" + account.getBalance() + "." ); } public void onButtonPressed() { int amount = getInt( "Amount" ); account.deposit( amount ); clearOutput(); println( "Balance is P" + account.getBalance() + "." ); } Class name Fields (data members) extends BankApplet1 “is a” IOApplet, and “inherits” code from it. (More later!)

Slide 16 Method Declaration ( ) { } public void deposit ( int amount ) { balance += amount; } Statements Modifier Return Type Method Name Parameter

Slide 17 Value-Returning Method We call a method that returns a value a value- returning method, or non-void method. A value-returning method must include a return statement in the following format: return ; public int getBalance( ) { return balance; }

Slide 18 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … aliceAccount BankAccount aliceBalance 100 int balance 1)Find object pointed to by aliceAccount 2)Find code for class of that object 3)Find code for getBalance() 4)Run code 5)Return value 6)Use returned value When the line above is run …

Slide 19 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … aliceAccount getBalance() BankAccount aliceBalance 100 int balance 1)Find object pointed to by aliceAccount 2)Find code for class of that object 3)Find code for getBalance() 4)Run code 5)Return value 6)Use returned value When the line above is run …

Slide 20 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … public class BankAccount { private int balance; // current amount public BankAccount() { // does nothing. defaults to balance=0 } public int getBalance() { return balance; } public void deposit( int amount ) { balance += amount; } BankAccount.java aliceAccount getBalance() BankAccount aliceBalance 100 int balance 1)Find object pointed to by aliceAccount 2)Find code for class of that object 3)Find code for getBalance() 4)Run code 5)Return value 6)Use returned value When the line above is run …

Slide 21 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … public class BankAccount { private int balance; // current amount public BankAccount() { // does nothing. defaults to balance=0 } public int getBalance() { return balance; } public void deposit( int amount ) { balance += amount; } BankAccount.java aliceAccount getBalance() BankAccount aliceBalance 100 int balance 1)Find object pointed to by aliceAccount 2)Find code for class of that object 3)Find code for getBalance() 4)Run code 5)Return value 6)Use returned value When the line above is run …

Slide 22 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … aliceAccount getBalance() BankAccount aliceBalance 100 int balance 1)Find object pointed to by aliceAccount 2)Find code for class of that object 3)Find code for getBalance() 4)Run code 5)Return value 6)Use returned value When the line above is run … public class BankAccount { private int balance; // current amount public BankAccount() { // does nothing. defaults to balance=0 } public int getBalance() { return balance; } public void deposit( int amount ) { balance += amount; } BankAccount.java public int getBalance() { return balance; }

Slide 23 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … public int getBalance() { return balance; } BankAccount.java aliceAccount getBalance() BankAccount aliceBalance 100 int balance 1)Find object pointed to by aliceAccount 2)Find code for class of that object 3)Find code for getBalance() 4)Run code 5)Return value 6)Use returned value When the line above is run … 100

Slide 24 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … public int getBalance() { return balance; } BankAccount.java aliceAccount getBalance() BankAccount aliceBalance 100 int balance 1)Find object pointed to by aliceAccount 2)Find code for class of that object 3)Find code for getBalance() 4)Run code 5)Return value 6)Use returned value When the line above is run … 100

Slide 25 Three Kinds of Variables Field (aka Attribute or Instance Variable) Variables declared inside a class’ code, but outside any methods Part of object’s “permanent” state Use for state that is retained between method calls Local Variable Variables declared inside a method definition Only exists while we’re inside the method Use as a “scratchpad” (temporary storage) during a computation Parameter Variables declared in the parentheses of a method definition Holds a copy of the value or reference passed as an argument to the method call Is also a local variable – i.e., only exists inside the method

Slide 26 Sample Method public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount= dollar * fee; return amount; } Parameter Local Variables Fields * * Although not shown here, exchangeRate and feeRate were declared inside the CurrencyConverter class, but outside any methods From Wu’s CurrencyConverter class …

Slide 27 Local Variables Example Code State of Memory amt = yenConverter.fromDollar( 200 ); public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } A A A. A. fromDollar’s local variables (amount and fee) do not exist before the method call At before fromDollar A A Currency Converter exchangeRate 5.0 feeRate yenConverter amt 0.0

Slide 28 Local Variables Example Code amt = yenConverter.fromDollar( 200 ); public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } B B B. B. Memory space is allocated for the local variables and parameter. Parameter’s value is copied from the argument. After is executed B B dollar amount fee State of Memory Currency Converter exchangeRate 5.0 feeRate yenConverter amt 0.0

Slide 29 amount fee Local Variables Example Code amt = yenConverter.fromDollar( 200 ); public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } C C C. C. Computed values are assigned to the local variables. After is executed C C dollar Currency Converter exchangeRate 5.0 feeRate yenConverter amt 0.0 State of Memory

Slide 30 amt Local Variables Example Code amt = yenConverter.fromDollar( 200 ); public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } D D D. D. Memory space for local variables and parameters is deallocated upon exiting the fromDollar method. At after fromDollar D D Currency Converter exchangeRate 5.0 feeRate yenConverter State of Memory

Slide 31 Three Kinds of Variables Field (aka Attribute or Instance Variable) Variables declared inside a class’ code, but outside any methods Part of object’s “permanent” state Use for state that is retained between method calls Local Variable Variables declared inside a method definition Only exists while we’re inside the method Use as a “scratchpad” (temporary storage) during a computation Parameter Variables declared in the parentheses of a method definition Holds a copy of the value or reference passed as an argument to the method call Is also a local variable – i.e., only exists inside the method

Slide 32 Passing Parameters Arguments are matched to parameters from left to right. Types must match The number of arguments in the method call must match the number of parameters in the method definition Arguments are passed to a method using the pass-by- value scheme Parameters and arguments do not have to have the same name Whether or not they have the same name, parameters are separate copies of the arguments Parameters are local to the method, i.e., they only exist while inside the method. Changes made to the parameters will not affect the value of corresponding arguments

Slide 33 Pass-By-Value Scheme State of Memory public void myMethod( int one, float two ) { one = 25; two = 35.4f; } A A A. A. Local variables do not exist before the method execution At before myMethod A A Code x = 10; y = 20; tester.myMethod( x, y ); xx 10 y 20

Slide 34 Pass-By-Value Scheme State of Memory B. B. The values of arguments are copied to the parameters. Values are copied at B B public void myMethod( int one, float two ) { one = 25; two = 35.4f; } Code x = 10; y = 20; tester.myMethod( x, y ); B B xx 10 y 20 one 10 two f

Slide 35 Pass-By-Value Scheme C C State of Memory C. C. The values of parameters are changed. After is executed C C public void myMethod( int one, float two ) { one = 25; two = 35.4f; } Code x = 10; y = 20; tester.myMethod( x, y ); xx 10 y 20 one 1025 two f

Slide 36 Pass-By-Value Scheme Code D D State of Memory D. D. Parameters are erased. Arguments remain unchanged. At after myMethod D D public void myMethod( int one, float two ) { one = 25; two = 35.4f; } x = 10; y = 20; tester.myMethod( x, y ); xx 10 y 20

Slide 37 Constructors A constructor is a special method that is called with the new command Used for initializing an object to a valid state Name of a constructor must be the same as the name of the class No return type If no constructor is defined, the Java compiler will include a default constructor with no arguments and no body

Slide 38 Defining Constructors A constructor will have the following form: public ( ) { } public BankAccount ( ) { } Currently, BankAccount’s constructor has no arguments and does nothing. Statements Modifier Class Name Parameter

Slide 39 Multiple Constructors A class can include multiple constructors without any problem, as long as the constructors defined for the class have either A different number of parameters Different data types for the parameters if the number of parameters is the same This is known as “overloading” and can also be done with ordinary methods public MyClass( int value ) { … } public MyClass( ) { … } public MyClass( float value ) { … } public MyClass( String name, float value ) { … } These constructors will not conflict with each other, and therefore, valid.

Slide 40 A Common Misconception public class StudentRecord { private String name; // current amount public StudentRecord( String name ) { } … methods (not shown) … } Some people think that you can set a field by simply giving the parameter same name as the field. THIS DOES NOT WORK. The parameter and the field are two different and independent variables, even if they have the same name.

Slide 41 The Correct Way (for now) public class StudentRecord { private String name; // current amount public StudentRecord( String initialName ) { name = initialName; } … methods (not shown) … } Give the parameter a different name in order to be clear. (We’ll discuss another way later.) Don’t forget to set the field through an assignment statement.

Slide 42 Access Modifiers public and private designate the accessibility of fields and methods private means code in other classes cannot access it public means anybody can access it no modifier means public within the same directory (more later when we get to “packages”) class Test { public int memberOne; private int memberTwo; } Test myTest = new MyTest(); myTest.memberOne = 10; myTest.memberTwo = 20; in another class …

Slide 43 Keeping fields private In general, fields should be private so we can have the flexibility of changing the implementation details of the class e.g., Suppose we want to keep a log of deposits if balance is public, we cannot guarantee that deposits will be logged because anyone can increment balance directly if balance is private, we can simply modify the deposit method Since users can only increment balance by calling deposit, all deposits will be logged. Users don’t even have to know that logging is taking place