CSE 1301 Lecture 6 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.

Slides:



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

© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 4: Writing Classes
Chapter 3, More on Classes & Methods Clark Savage Turner, J.D., Ph.D. Copyright 2003 CSTurner, from notes and text.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter Day 7. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 7 Questions from last Class?? Problem set 1 Corrected  Good results 3.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Methods in Java Selim Aksoy Bilkent University Department of Computer Engineering
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley John Lewis, Peter DePasquale, and Joseph Chase Chapter 5: Writing Classes.
Writing Classes (Chapter 4)
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
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 Programming Part 2: User-Defined Classes.
CPS120: Introduction to Computer Science Functions.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Chapter 4 Writing Classes Part 2. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Classes A class can contain data declarations and method declarations.
CSE 1301 Lecture 5 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Procedural programming in Java Methods, parameters and return values.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 4 Introduction to Classes, Objects, Methods and strings
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Wednesday –POD –I have updated grades in powerschool. If you have a zero for a lab grade, it probably means you didn’t DropItToMe. Please do so. –Slides.
Lecture 4 b Writing Classes b class declarations b method declarations b constructors b instance variables b encapsulation b method overloading b program.
Chapter 4: Writing Classes. 2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter 4 focuses.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Chapter 4 Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 7 User-Defined Methods.
Chapter 4: Writing Classes
Chapter 4: Writing Classes
Lecture 14 Writing Classes part 2 Richard Gesick.
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.
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Anatomy of a Method.
Chapter 4 Writing Classes.
CS139 October 11, 2004.
Object-Oriented Programming
Classes, Objects and Methods
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Object-Oriented Design AND CLASS PROPERTIES
Object-Oriented Design AND CLASS PROPERTIES
Presentation transcript:

CSE 1301 Lecture 6 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick

CSE 1301 Topics Methods Return Parameters Constructors Overloading Constructors Scope

CSE 1301 Method Declarations Let’s now examine method declarations in more detail A method declaration specifies the code that will be executed when the method is invoked (called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined

CSE 1301 Methods Used to group a set of instructions Given a name (so we can refer to it later) This name represents the instructions Methods can be public or private – Public if someone outside the class should access/invoke them – Private if used internal to the class

CSE 1301 myMethod(); myMethodcompute Method Control Flow If the called method is in the same class, only the method name is needed

CSE 1301 doIt helpMe helpMe(); obj.doIt(); main Method Control Flow The called method is often part of another class or object

CSE 1301 A Method Returns When the method is done, control returns to where we “left off” in the caller As in math, functions/methods can evaluate to something – We should be able to “return” a value The return statement halts execution within the method and (optionally) returns a value

CSE 1301 Return Example int Sum(int a, int b) { return a + b; Console.Writeline("This will never be displayed"); }

CSE 1301 Method Header A method declaration begins with a method header char calc (int num1, int num2, string message) method name return type parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter

CSE 1301 Method Body The method header is followed by the method body char calc (int num1, int num2, string message) { int sum = num1 + num2; char result = message.charAt(sum); return result; } The return expression must be consistent with the return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing

CSE 1301 Method Body The code that performs the method's function is written between the beginning and ending curly braces. In the method body, a method can declare variables, call other methods, and use other program structures (if/else statements, while loops, for loops, switch statements, and do/while loops)

CSE 1301 The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type A return statement specifies the value that will be returned return expression; Its expression must conform to the return type

CSE 1301 Parameters & Scope Because variables are only visible within the scope in which they are declared, no one else can “see” them This is a good thing for protection/encapsulation But we need a way of moving data within our program – Making everything “global” is a bad idea – There are times when we need to pass on some data to the method for it to work on that data

CSE 1301 Parameters A method is defined by its – Name – Return type – PARAMETERS (the stuff in the parenthesis) When we call a method, we need to pass the correct number and type of parameters – “Speak the language” of the method

CSE 1301 Parameters When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header char calc (int num1, int num2, string message) { int sum = num1 + num2; char result = message.charAt(sum); return result; } ch = obj.calc (25, count, "Hello");

CSE 1301 Constructors Special methods that are called when an object is instantiated using the new keyword. A class can have several constructors. The job of the class constructors is to initialize the instance variables of the new object.

CSE 1301 Constructors So far, we’ve seen attributes and methods Constructor is a unique method – Named same as the class name – Automatically called when class is instantiated – Useful for setting attributes & initializing the instance – No return type (not even void) – Must be public Default constructor is used unless you specify a constructor For each attribute in the class, assign something to it in the constructor (initialize)

CSE 1301 class BMW_Z4 { private int modelYear; private string licensePlate; private bool topUp; public BMW_Z4 () { ModelYear = 2004; TopUp = false; LicensePlate = "DEALER"; }... } Constructor Example

CSE 1301 Multiple Constructors (overloading) Constructors are used to initialize our objects We can use parameters to the constructor to customize the initialization Sometimes we have more or less data to use in the customization We’d like to be able to pass in only what we know 1-19

CSE 1301 Overloading Overloading involves using the same method/function name – Vary the number of parameters – Vary the type of parameters – Cannot just change return type (ambiguity in invocation) Useful to keep things simple – Squaring a number…

CSE 1301 Overloading Example int Square (int i) { return i * i; } float Square (float i) { return i * i; } static void Main() {... float x = Square(5.3f); int y = Square(9);... }

CSE 1301 Constructor Overloading class BMW_Z4 {... public BMW_Z4 () { Initialize(0, 2004, false); } public BMW_Z4 (int my) { Initialize(0, my, false); } private Initialize(int cs, int my, bool tu) { currentSpeed = cs; ModelYear = my; TopUp = tu; }... } Place common initialization in a separate function Notice same method name, different parameters

CSE 1301 Which is Called? BMW_Z4 myCar = new BMW_Z4(); BMW_Z4 yourCar = new BMW_Z4(2007); BMW_Z4 herCar = new BMW_Z4(2008); The constructor with the matching parameter definition will be called – If no parameters, the () constructor – If one parameter, the (int) constructor 2-23 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison- Wesley

CSE 1301 Defining a Constructor Syntax: public ClassName( parameter list ) { // constructor body } Note: no return value, not even void! Each constructor must have a different number of parameters or parameters of different types Default constructor: a constructor that takes no arguments.

CSE 1301 Constructor Examples public class Card { private int value; private string suit; //default constructor public Card ( ) { value = 1; suit = “Spades”; } // specific constructor public Card (int initValue, string initSuit) { value = initValue; suit = initSuit; }

CSE 1301 Class Scope Instance variables have class scope – Any constructor or method of a class can directly refer to instance variables. Methods also have class scope – Any method or constructor of a class can call any other method of a class (without using an object reference).

CSE 1301 Local Scope A method's parameters have local scope, meaning that: – a method can directly access its parameters. – a method's parameters cannot be accessed by other methods. A method can define local variables which also have local scope, meaning that: – a method can access its local variables. – a method's local variables cannot be accessed by other methods.

CSE 1301 Summary of Scope A method in a class can access: – the instance variables of its class – any parameters sent to the method – any variable the method declares from the point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first – any methods in the class

CSE 1301 Accessor Methods Clients cannot directly access private instance variables, so classes provide public accessor methods with this standard form: public returnType getInstanceVariable( ) { return instanceVariable; } (returnType is the same data type as the instance variable) This is the same as the “get” property.

CSE 1301 Accessor Methods Example: the accessor method for model from the Auto class public string getModel( ) { return model; }

CSE 1301 Mutator Methods Allow client to change the values of instance variables public void setInstanceVariable( dataType newValue ) { // validate newValue, // then assign to instance variable } This is the same as the “set” property.

CSE 1301 Software Engineering Tip Write the validation code for the instance variable in the mutator method and have the constructor call the mutator method to validate and set initial values This eliminates duplicate code and makes the program easier to maintain

CSE 1301 Common Error Trap Do not declare method parameters. – Parameters are defined already and are assigned the values sent by the client to the method. Do not give the parameter the same name as the instance variable. – The parameter has name precedence so it "hides" the instance variable. Do not declare a local variable with the same name as the instance variable. – Local variables have name precedence and hide the instance variable.

CSE 1301 The Object Reference this How does a method know which object's data to use? this is an implicit parameter sent to methods and is an object reference to the object for which the method was called. When a method refers to an instance variable name, this is implied Thus: variableName model is understood to be is understood to be this.variableName this.model

CSE 1301 Using this in a Mutator Method public void setInstanceVariable( dataType instanceVariableName ) { this.instanceVariableName = instanceVariableName; } Example: public void setModel( string model ) { this.model = model; } this.model refers to the instance variable. model refers to the parameter.

CSE 1301 Another Example Suppose we wanted a new object to represent a day of the year. What data should we store? What operations are available? What should be public? What should be private?

CSE 1301 static Variables Also called class variables One copy of a static variable is created per class static variables are not associated with an object static constants are often declared as public To define a static variable, include the keyword static in its definition: Syntax: accessSpecifier static dataType variableName; Example: public static int countAutos = 0;

CSE 1301 static Methods Also called class methods Often defined to access and change static variables static methods cannot access instance variables: – static methods are associated with the class, not with any object. – static methods can be called before any object is instantiated, so it is possible that there will be no instance variables to access.

CSE 1301 Rules for static and Non-static Methods static Method Non-static Method Access instance variables?noyes Access static class variables? yes Call static class methods?yes Call non-static instance methods? noyes Use the object reference this? noyes