PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods.

Slides:



Advertisements
Similar presentations
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Advertisements

Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Road Map Introduction to object oriented programming. Classes
VBA Modules, Functions, Variables, and Constants
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
© 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.
XP New Perspectives on Microsoft Office Access 2003 Tutorial 11 1 Microsoft Office Access 2003 Tutorial 11 – Using and Writing Visual Basic for Applications.
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
© 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Local Variables Garbage collection. © 2006 Pearson EducationParameters2 of 10 Using Accessors and Mutators Together What if you want to get a property.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
© 2006 Pearson Education Inheritance 1 of 31 INHERITANCE Class Hierarchies Extending Objects Abstract Methods Abstract Classes Overriding Methods protected.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
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:
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 5 Introduction to Defining Classes
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
© 2006 Pearson EducationMaking Objects 1 of 36 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods Sending.
Introduction to Object-Oriented Programming Lesson 2.
© 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Module 9: Operator overloading #1 2000/01Scientific Computing in OOCourse code 3C59 Module 9: Operator Overloading In this module we will cover Overloading.
What is an object?. What Makes an Object? An object has identity (it acts as a single whole). Every object has a name that identifies what it is. Ex.
Today Encapsulation. Build a fully encapsulated Halloween class, going from Halloween1 to Halloween6 (eventually!): –The final version will have overloaded.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
User-Written Functions
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
Classes.
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.
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
Compiler Design 18. Object Oriented Semantic Analysis (Symbol Tables, Type Checking) Kanat Bolazar March 30, 2010.
Java Programming Language
Tonga Institute of Higher Education
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Java Programming Language
Classes, Objects and Methods
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Classes and Objects Object Creation
Creating and Using Classes
CMSC 202 Constructors Version 9/10.
Presentation transcript:

PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education Parameters2 of 32 Problem 1: Making Messages Specific CSMobile needs a paint job! Let’s say we want to give CSMobile the capability of being painted different colors One solution: –add a method to CSMobile for each color we want to paint with public void setRed(); public void setBlue(); public void setTeal(); public void setMauve();... Not very elegant to write all these methods Much more efficient to write one setColor method in class CSMobile in which we could specify the color that we want to paint with How do we make a message specific?

© 2006 Pearson Education Parameters3 of 32 Problem 2: A Smart CSMobile CSMobile is going for a drive! It’s time to associate CSMobile with the City it’s driving in –so that it can call methods on class City to ask where schools and parks are located Remember, City contains CSMobile –City can automatically call methods on CSMobile But containment relationship is not symmetric –CSMobile can’t automatically call methods on City So how can we enable CSMobile to know its container, City, so it can call methods on City ? Need to associate a City instance with a CSMobile instance in order for a CSMobile to call methods on City. How do we associate two objects?

© 2006 Pearson Education Parameters4 of 32 Parameters Answer: Parameters! We use Parameters in 2 cases: 1) To make messages between objects specific by sending additional information –in a setColor() method, we can specify color –in an eat() method, we can specify food 2) For one object to learn about another object that it didn’t create –can use a method to let a CSMobile know about the City it is driving in –this is the way to set up association (“knows-about”) relationships But how?

© 2006 Pearson Education Parameters5 of 32 Sending and Receiving A sending method sends specifics of a given situation to a receiving method This is what the parentheses after the method names are for –parameters are variables that go inside the parentheses In fact, you already know parameters quite well –a function in math is like a method that receives one or more parameters and computes a result –“send” the function a specific value of the parameter –example: setColor() green f(x) = x 2 + 2x specifics receiving method specific valuereceiving function

© 2006 Pearson Education Parameters6 of 32 x is a Formal parameter –formal parameters are “dummy” variables that represent instances sent when calling a method –have no value of their own; take on value of parameters passed in when method is called –placeholders, like x in x 2 + 2x is an Actual parameter –actual parameters are “actual” instances sent when calling method –specific values passed with message from sender to receiver f(x) = x 2 + 2x + 5 Let’s see a method that receives parameters! Formal and Actual Parameters 213 actual parameter formal parameter returns

© 2006 Pearson Education Parameters7 of 32 /** * This class models a CSMobile that * can be painted any color. The instance * variables and other methods that we defined * in earlier lectures are elided for brevity. */ public class CSMobile { private java.awt.Color _color; // other instance variable declarations elided public CSMobile() { _color = java.awt.Color.white; // default // other instance variable definitions elided } public void setColor( java.awt.Color newColor ){ _color = newColor; // now paint the car using the color // we have stored in _color } // other methods elided } Syntax: The Receiver formal parameter

© 2006 Pearson Education Parameters8 of 32 /** * This simple App only sends the CSMobile’s * brand new setColor method a parameter. */ public class SimpleApp extends wheels.users.Frame { private CSMobile _csMobile; public SimpleApp() { _csMobile = new CSMobile(); _csMobile.setColor( java.awt.Color.blue ); } public static void main ( String[] argv ) { SimpleApp app = new SimpleApp(); } } Syntax: The Sender actual parameter

© 2006 Pearson Education Parameters9 of 32 Syntax for the Receiver Syntax for class CSMobile : private java.awt.Color _color; –java.awt.Color is the built-in Java class that represents a color –CSMobile has an instance variable representing its color, set in its constructor _color = java.awt.Color.white; // default –java.awt.Color.white is a constant –java.awt.Color class has many predefined constant colors which are public instance variables of the Color class (examples: red, green, blue, white ) –okay for them to be public instance variables because they are constant (cannot be changed!) so don’t need to worry about value changing unexpectedly –more on how you can create constants later in the course

© 2006 Pearson Education Parameters10 of 32 More Syntax for the Receiver public void setColor( java.awt.Color newColor ) { –example of a method that receives a parameter –parameter is of type java.awt.Color tells Java that this method “takes in” an instance of the java.awt.Color class when it is called –newColor is a formal parameter a.k.a. the name that the parameter will be referred to in this method can only use newColor within setColor() method –a method that receives one parameter is always of the form methodName(param-type param-name) we often record the parameter in an instance variable _color = newColor; read: _color “gets” the same Color as newColor (i.e., whatever value newColor was set to by sender) type that method expects formal parameter (name)

© 2006 Pearson Education Parameters11 of 32 Syntax for the Sender Syntax for class SimpleApp : _csMobile.setColor( java.awt.Color.blue ); –example of a method call that sends a parameter –here, we send the constant java.awt.Color.blue as an actual parameter to the receiving method, setColor() –note: don’t specify the type of the parameter you “pass in” (in this case, java.awt.Color ) this is because the parameter type is already specified in the CSMobile class if you tried to pass in something that wasn’t a Color, you would get a compile error like: Incompatible type for method. Can’t convert somethingBad to Color. actual parameter (value)

© 2006 Pearson Education Parameters12 of 32 More on Actual and Formal Parameters One-to-one correspondence between formal and actual parameters –order, type (class) of instances, and number of parameters sent must match order, type, and number declared in method! _csMobile.setColor(java.awt.Color.blue) sends one parameter of type java.awt.Color matches public void setColor( java.awt.Color newColor ) expects one parameter of type java.awt.Color Name of formal parameter does not have to be the same as the corresponding actual parameter –receiver cannot know what specific instances will be passed to it, yet it must know how to refer to it so receiver uses a dummy name to represent the parameter –sender may send different actual parameters may send red, blue, yellow, etc. to setColor() method

© 2006 Pearson Education Parameters13 of 32 Signatures The combination of the method identifier, the class of its parameters, and the order of its parameters is called the method’s signature. –Like a person’s signature, a method’s signature must be unique. –Trying to provide two methods in one class with the same signature will cause an error like: duplicateMethod() is already defined in MyClass: public void duplicateMethod();

© 2006 Pearson Education Parameters14 of 32 References as Values of Variables To send messages to an object, we must have a name for it –in Java, can only access objects via references to them Objects do not contain actual component objects, only references to them _color java.awt.Color The equals operator actually assigns references _csMobile = new CSMobile(); makes _csMobile refer to a new instance of class CSMobile i.e., _csMobile is assigned a reference to an instance created by CSMobile() _color = newColor; makes _color refer to the same instance of Color class that newColor does i.e., _color is assigned the same color as newColor refers to an instance of

© 2006 Pearson Education Parameters15 of 32 Review: References Revealed References are just pointers to memory –human readable versions of addresses –easier to keep track of names than weird numbers (like 0xeff8a9f4 ) –holds memory address where instance is stored –Java also has primitives, which are not objects and do not have pointers (more on this later) reference to instance 1 reference to instance 2 reference to instance 3

© 2006 Pearson Education Parameters16 of 32 Formal parameters refer to the same instance as actual parameters after the method is called –i.e., they are different names for the same instance –so, calling a method on instance referred to by formal parameter is the same as calling the method on instance referred to by actual parameter (not the same as in some other programming languages!) public class SimpleApp {... _csMobile.setColor(java.awt.Color.blue);... } public class CSMobile {... public void setColor(java.awt.Color newColor) {... } } java.awt.Color Parameters as References Actual parameter Formal parameter SENDERSENDER RECEIVERRECEIVER

© 2006 Pearson Education Parameters17 of 32 Parameters and Association Finally, the moment you’ve all been waiting for... Let’s use what we’ve learned about parameters to enable a CSMobile to know about its City -- called association –CSMobile can store a reference to its City so that it can send messages to it Usually associations are done in the constructor –don’t forget that constructors are methods, too –they can receive parameters just like any other method Let’s see all this in action...

© 2006 Pearson Education Parameters18 of 32 Syntax: The Receiver /** * This class models a CSMobile that * knows about its City. Again, the instance * variables, constructor, and other * methods that we defined in earlier * slides are elided. */ public class CSMobile { private City _city; public CSMobile(City myCity) { _city = myCity; } } So whoever instantiates a CSMobile is expected to pass in a City to the CSMobile’s constructor for the CSMobile to be associated with. This City will be temporarily referenced by the formal parameter myCity which is then permanently assigned to the instance variable _ city. Now the CSMobile can call methods on the City.

© 2006 Pearson Education Parameters19 of 32 Syntax: The Sender /** * This class models a city * where CSMobiles exist. Because the * City contains the CSMobile, it can * send the CSMobile the reference to * an instance of itself. */ public class City { private CSMobile _csMobile; public City() { _csMobile = new CSMobile(this); } } In this case, the “whoever” mentioned on the previous slide is the City itself. It passes the CSMobile a reference to itself by using the reserved word this. Now _csMobile is associated with “this” instance of City.

© 2006 Pearson Education Parameters20 of 32 Syntax for the Receiver Syntax for class CSMobile : private City _city; –CSMobile has a variable representing the City that it is driving in // CSMobile constructor public CSMobile( City myCity ) { _city = myCity; } –standard constructor that receives a parameter –assigns the parameter passed in, myCity, to the instance variable, _city –CSMobile now knows about myCity

© 2006 Pearson Education Parameters21 of 32 Syntax for the Sender Syntax for class City : _csMobile = new CSMobile( this ); Remember this (“Making Objects” lecture, slide 23)? –shorthand for “this instance”, i.e., instance of the class where execution is currently taking place Constructor for CSMobile needs a City –we need to pass an instance of the City class to the constructor for CSMobile –where can we find an instance of City ? –since we’re in the City class constructor (i.e., execution is taking place inside the City class), we can use this as our instance of City _csMobile = new CSMobile(this); public CSMobile( City myCity ) Actual parameter sent by city Formal parameter used by CSMobile constructor S R City

© 2006 Pearson Education Parameters22 of 32 Methods with Multiple Parameters Declaring a method that accepts more than one parameter is quite simple –for example, let’s say that the CSMobile is about to get a speeding ticket! –an instance of the Policeman class needs to know about the CSMobile as well as the City in order to write up the ticket –choice of “hardwiring” particular City in Policeman constructor or allowing City to be totally dynamic in a method like this: public void giveTicket(City myCity, CSMobile car) { } method would be called like this: _policeman.giveTicket(_city, _csMobile); Formal parameters instance of class Policeman instance of class City instance of class CSMobile

© 2006 Pearson Education Parameters23 of 32 Method Overloading What if we usually want to repaint the CSMobile red? –assume the CSMobile starts as white –don’t want to have to specify a red color each time –but still want to have the capability to paint it a color other than red Method overloading lets you make multiple versions of the same method with different parameters –method name is the same, but parameter lists are different so the methods’ signatures are different –parameters must be different in type, not just in name –allows further customization of methods Let’s see it!

© 2006 Pearson Education Parameters24 of 32 CSMobile with Method Overloading /** * This class demonstrates method * overloading in the CSMobile. */ public class CSMobile { private java.awt.Color _color; public CSMobile() { _color = java.awt.Color.white; // default } public void setColor(java.awt.Color newColor){ _color = newColor; } public void setColor() { this.setColor( java.awt.Color.red ); } }

© 2006 Pearson Education Parameters25 of 32 Method Overloading Syntax Explained Note: Two methods with the same name, but different lists of parameters public void setColor( java.awt.Color newColor ) (1 parameter) public void setColor() ( 0 parameters) Example of a method that calls another: public void setColor() { this.setColor( java.awt.Color.red ); } –often when you overload, you call a different version of the method with different parameters –in this case, adding the default value –advantages: less code (except in trivial situations like this one) less room for error —much easier to find and fix errors in one method that other methods depend on than to fix the same error in many methods –advantages over procedural programming: no ugly case/switch statements (we’ll cover them later) avoids unpredictability of default parameters

© 2006 Pearson Education Parameters26 of 32 Return Types Let’s say we want to ask the CSMobile for its color Just like methods can take in information, they can also give back information (remember the example of a function that computes a result) Methods can send a response back to the object that called the method First, method must specify what type of object it responds with –type takes the place of void in the method declaration Then, at end of method it returns an object of the declared type to the calling method How does this look? Sending Object Receiving Object Method message optional return

© 2006 Pearson Education Parameters27 of 32 Return Types /** * This class demonstrates the * CSMobile using return types. */ public class CSMobile { private java.awt.Color _color; public CSMobile() { _color = java.awt.Color.white; } // setColor methods elided public java.awt.Color getColor() { return _color; } }

© 2006 Pearson Education Parameters28 of 32 Return Types Syntax Explained public java.awt.Color getColor() –note that instead of void, method says java.awt.Color –the void keyword means the method returns nothing –void can be replaced with a class type any object of appropriate type can be returned something that calls the getColor method will expect a java.awt.Color to be returned to it example: _carcolor = _csMobile.getColor(); return _color; –at the end of a method, use the return keyword to give back an object of the appropriate class type –_color is a java.awt.Color so it can be returned by the getColor method instance variable of type Color instance variable of type CSMobile

© 2006 Pearson Education Parameters29 of 32 Accessors and Mutators (1 of 3) Accessor and Mutator methods are simple helper methods for getting or setting one property of an object These methods are very simple but illustrate the concepts of parameters and return types Mutator Methods: –“set” methods –use parameters but generally not a return type (return void ) –exist primarily to change the value of a particular private instance variable (property) in a safe way as we will learn in later lectures, it allows a programmer to prevent variables from being set to bad (error) values, like null –names usually start with set ( setColor, setSize, setCity ) –Examples, respectively: method to set the color of an object method to set the size of an object method to set the city that a CSMobile drives in

© 2006 Pearson Education Parameters30 of 32 Accessors and Mutators (2 of 3) Accessor Methods: –“get” methods –use return types but generally not parameters (parentheses after the method name are empty) –exist primarily to return information to the calling method –names usually start with get ( getColor, getSize, getCity ) –Examples, respectively: method that returns the color of an object method that returns the size of an object method that returns the city that a CSMobile drives in Accessors and mutators usually occur in pairs public void setColor(java.awt.Color newColor) method of CSMobile was really just a mutator public java.awt.Color getColor() method of CSMobile was really just an accessor

© 2006 Pearson Education Parameters31 of 32 Accessors and Mutators (3 of 3) What we recommend you should do: –use helper (accessor and mutator) methods to give a class safe access to other class’ instance variables (if necessary) What we recommend you never do (although it is legal Java syntax): public class CSMobile { //a public instance variable!! public java.awt.Color _color; public CSMobile() { _color = java.awt.Color.white; } } public class City { private CSMobile _car; public City() { _car = new CSMobile(); //accessing a public instance variable _car._color = java.awt.Color.red; } } This allows another class to change the value of _color without the CSMobile knowing. This means the CSMobile cannot check for bad colors (like puke green) and will not know that it should go get the new paint job! USE ACCESSORS AND MUTATORS, NOT PUBLIC INSTANCE VARIABLES!!!

© 2006 Pearson Education Parameters32 of 32