Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
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.
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Chapter 4: Writing Classes
Road Map Introduction to object oriented programming. Classes
Chapter 3, More on Classes & Methods Clark Savage Turner, J.D., Ph.D. Copyright 2003 CSTurner, from notes and text.
©2004 Brooks/Cole Chapter 6 Methods. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Using Methods We've already seen examples of using methods.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Enhancing classes Visibility modifiers and encapsulation revisited
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP Introduction to Programming Adrian Ilie July 13, 2005.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Class design. int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations.
Defining Classes and Methods Chapter 4.1. Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
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.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Building java programs, chapter 3 Parameters, Methods and Objects.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
By Mr. Muhammad Pervez Akhtar
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
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.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
C# Programming Methods.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Classes - Intermediate
Methods main concepts – method call – object 's methods – actual parameters – method declaration – formal parameters – return value other concepts – method.
CPSC 233 Tutorial 5 February 9 th /10 th, Java Classes Each Java class contains a set of instance variables and methods Instance Variables: Type.
© 2004 Pearson Addison-Wesley. All rights reserved November 12, 2007 Inheritance ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Lecture 02 Dr. Eng. Ibrahim El-Nahry Methods. 2 Learning Objectives Class Definition includes both methods and data properties Method Definition and Declaration.
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.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Functions + Overloading + Scope
Chapter 7 User-Defined Methods.
AKA the birth, life, and death of variables.
Chapter 4: Writing Classes
Methods.
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.
Chapter 6 Methods: A Deeper Look
Starting Out with Java: From Control Structures through Objects
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through.
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
CHAPTER 6 GENERAL-PURPOSE METHODS
CS2011 Introduction to Programming I Methods (II)
Chapter 6 Methods.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Corresponds with Chapter 5
Presentation transcript:

Methods

int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors) Data declarations Method declarations

Methods A program that provides some functionality can be long and contains many statements A method groups a sequence of statements and should provide a well-defined, easy-to-understand functionality –a method takes input, performs actions, and produces output In Java, each method is defined within specific class

Method Declaration: Header A method declaration begins with a method header methodname returntype 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 argument class MyClass { static int min ( int num1, int num2 ) … properties

Method Declaration: Body The header is followed by the method body: static int min(int num1, int num2) { int minValue = num1 < num2 ? num1 : num2; return minValue; } class MyClass { … … }

6 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 The return statement specifies the value that will be returned –Its expression must conform to the return type

Calling a Method Each time a method is called, the values of the actual arguments in the invocation are assigned to the formal arguments static int min (int num1, int num2) { int minValue = (num1 < num2 ? num1 : num2); return minValue; } int num = min (2, 3);

Method Control Flow A method can call another method, who can call another method, … min(num1, num2, num3) println() …println(…) min(1, 2, 3); main

9 Method Overloading A class may define multiple methods with the same name---this is called method overloading –usually perform the same task on different data types Example: The PrintStream class defines multiple println methods, i.e., println is overloaded: println (String s) println (int i) println (double d) … The following lines use the System.out.print method for different data types: System.out.println ("The total is:"); double total = 0; System.out.println (total);

10 Method Overloading: Signature The compiler must be able to determine which version of the method is being invoked This is by analyzing the parameters, which form the signature of a method –the signature includes the type and order of the parameters if multiple methods match a method call, the compiler picks the best match if none matches exactly but some implicit conversion can be done to match a method, then the method is invoke with implicit conversion. –the return type of the method is not part of the signature

Method Overloading double tryMe (int x) { return x +.375; } Version 1 double tryMe (int x, double y) { return x * y; } Version 2 result = tryMe (25, 4.32)Invocation

More Examples double tryMe ( int x ) { return x + 5; } double tryMe ( double x ) { return x *.375; } double tryMe (double x, int y) { return x + y; } tryMe( 1 ); tryMe( 1.0 ); tryMe( 1.0, 2); tryMe( 1, 2); tryMe( 1.0, 2.0); Which tryMe will be called?

Variable Scoping

Variables At a given point, the variables that a statement can access are determined by the scoping rule –the scope of a variable is the section of a program in which the variable can be accessed (also called visible or in scope) There are two types of scopes in Java –class scope a variable defined in a class but not in any method –block scope a variable defined in a block {} of a method; it is also called a local variable

Java Scoping Rule A variable with a class scope –class/ static variable: a variable defined in class scope and has the static property it is associated with the class and thus can be accessed (in scope) in all methods in the class –instance variable: a variable defined in class scope but not static it is associated with an instance of an object of the class, and thus can be accessed (in scope) only in instance methods, i.e., those non-static methods A variable with a block scope –can be accessed in the enclosing block; also called local variable –a local variable can shadow a variable in a class scope with the same name Do not confuse scope with duration –a variable may exist but is not accessible in a method, e.g., method A calls method B, then the variables declared in method A exist but are not accessible in B.

Scoping Rules (cont.): Variables in a method There are can be three types of variables accessible in a method : –class and instance variables static and instance variables of the class –local variables those declared in the method –formal arguments

Example1: public class Box { private int length, width; … public int widen (int extra_width) { private int temp1; size += extra_width; … } public int lenghten (int extra_lenth) { private int temp2; size += extra_length; … } … } instance variables formal arguments local variables

Scope of Variables Instance variables are accessible in all methods of the class formal arguments are valid within their methods Local variables are valid from the point of declaration to the end of the enclosing block public class Box { private int length, width; … public int widen (int extra_width) { private int temp1; size += extra_width; … } public int lenghten (int extra_lenth) { private int temp2; size += extra_length; … } … }

public class Test { final static int NO_OF_TRIES = 3; static int i = 100; public static int square ( int x ) { // NO_OF_TRIES, x, i in scope int mySquare = x * x; // NO_OF_TRIES, x, i, mySquare in scope return mySquare; } public static int askForAPositiveNumber ( int x ) { // NO_OF_TRIES, x, i in scope for ( int i = 0; i < NO_OF_TRIES; i++ ) { // NO_OF_TRIES, x, i in scope; local i shadows class i System.out.print(“Input: “); Scanner scan = new Scanner( System.in ); String str = scan.nextLine(); int temp = Integer.parseInt( str ); // NO_OF_TRIES, x, i, scan, str, temp in scope if (temp > 0) return temp; } // NO_OF_TRIES, x, i in scope return 0; } // askForPositiveNumber public static void main( String[] args ) {…} }

Two Types of Parameter Passing If a modification of the formal argument has no effect on the actual argument, –it is call by value If a modification of the formal argument can change the value of the actual argument, –it is call by reference

Call-By-Value and Call-By-Reference in Java Depend on the type of the formal argument If a formal argument is a primitive data type, a modification on the formal argument has no effect on the actual argument –this is call by value, e.g. num1 = min(2, 3); num2 = min(x, y); This is because primitive data types variables contain their values, and procedure call trigger an assignment: = int x = 2; int y = 3; int num = min (x, y); … static int num( int num1, int num2) { … } int x = 2; int y = 3; int num1 = x; int num2 = y; { … }

Call-By-Value and Call-By-Reference in Java If a formal argument is not a primitive data type, an operation on the formal argument can change the actual argument –this is call by reference This is because variables of object type contain pointers to the data that represents the object Since procedure call triggers an assignment = it is the pointer that is copied, not the object itself! MyClass x = new MyClass(); MyClass y = new MyClass(); MyClass.swap( x, y); … static void swap( MyClass x1, MyClass x2) { … } x = new MC(); y = new MC(); x1 = x; x2 = y; { … }

Class design

24 Classes define Objects In object-oriented design, we group methods together according to objects on which they operate An object has: –state - descriptive characteristics –behaviors - what it can do (or be done to it), may depend on the state, and can change the state For example, a calendar program needs Month objects: –the state of a Month object is a (month,year) pair of numbers –these are stored as instance variables of the Month class –the Month class can also have class variables, e.g. the day of the week that Jan 1, 2000 falls on… –some behaviors of a month object are: get name, get first weekday, get number of days, print set month index, set year

int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations Method declarations

Method Types There can be various types of methods (behavior declarations) –access methods : read or display states (or those that can be derived) –predicate methods : test the truth of some conditions –action methods, e.g., print –constructors: a special type of methods they have the same name as the class –there may be more then one constructor per class (overloaded constructors) they do not return any value –it has no return type, not even void they initialize objects of the class, using the new construct: –e.g. m1 = new Month() ; you do not have to define a constructor –the value of the state variables have default value

Example: Month class We define a Month class to model a month in the calendar program In our Month class we could define the following data: –month, an integer that represents the index of month –year, an integer that represents the year the month is in We might also define the following methods: –a Month constructor, to set up the month –a getName method, to ask for the string name of a month obj. –a getNumberOfDays method, to ask for the no. of days of a month object –a getFirstWeekday method, to ask for the weekday of the first day of a month object –a print method, to print the month calendar –a setMonth method, to ask a month object to change its month –a setYear object, to ask a month object to change its year