Methods. Methods. Mysteries Revealed

Similar documents
Methods and Data (Savitch, Chapter 5)

method method public class Temperature { public static void main(string[] args) { // your code here } new

Classes. Classes as Code Libraries. Classes as Data Structures

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

Learning objec<ves. Classes, Objects, and Methods. Problem Decomposi<on. Problem Decomposi<on (cont d)

Defining Classes and Methods

5. Defining Classes and Methods

Objectives. Defining Classes and Methods. Objectives. Class and Method Definitions: Outline 7/13/09

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

5. Defining Classes and Methods

Defining Classes and Methods

Chapter 4 Defining Classes I

Defining Classes and Methods

Chapter 6 Introduction to Defining Classes

CS 251 Intermediate Programming Methods and Classes

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Declaring and ini,alizing 2D arrays

CS 251 Intermediate Programming Methods and More

Introduction to Programming Using Java (98-388)

Array Basics: Outline

Defining Classes and Methods

Defining Classes and Methods

Chapter 4. Defining Classes I

EECS168 Exam 3 Review

Defining Classes and Methods

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Array Basics: Outline

by Pearson Education, Inc. All Rights Reserved. 2

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS112 Lecture: Defining Instantiable Classes

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Object Oriented Programming in C#

Programming II (CS300)

COMP Information Hiding and Encapsulation. Yi Hong June 03, 2015

Programming II (CS300)

Java+- Language Reference Manual

CS 231 Data Structures and Algorithms, Fall 2016

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

Cpt S 122 Data Structures. Introduction to C++ Part II

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Chapter 4. Defining Classes I

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Chapter 4: Writing Classes

A Founda4on for Programming

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Anatomy of a Class Encapsulation Anatomy of a Method

Programming II (CS300)

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

OBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com

Lecture 04 FUNCTIONS AND ARRAYS

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Abstract Data Types

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Ticket Machine Project(s)

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

3.1 Class Declaration

Computer Programming, I. Laboratory Manual. Final Exam Solution

An overview of Java, Data types and variables

Introduction to Programming (Java) 4/12

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object-Oriented Programming Concepts

PROGRAMMING FUNDAMENTALS

CHAPTER 7 OBJECTS AND CLASSES

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Defining Classes. Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining

Full file at

Java Object Oriented Design. CSC207 Fall 2014

Java and OOP. Part 2 Classes and objects

Lecture 7: Classes and Objects CS2301

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

JAVA GUI PROGRAMMING REVISION TOUR III

( &% class MyClass { }

Program Fundamentals

CS111: PROGRAMMING LANGUAGE II

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

JAVA Programming Concepts

CS112 Lecture: Working with Numbers

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Array Basics: Outline

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

CS1004: Intro to CS in Java, Spring 2005

Objects as a programming concept

Topic 3 Encapsulation - Implementing Classes

Object Oriented Programming

Encapsula)on CMSC 202

Java Bytecode (binary file)

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Objects and Classes -- Introduction

Lecture 02, Fall 2018 Friday September 7

Transcription:

Methods Methods and Data (Savitch, Chapter 5) TOPICS Invoking Methods Return Values Local Variables Method Parameters Public versus Private A method (a.k.a. func2on, procedure, rou2ne) is a piece of code that performs a useful ac2on. Up to this point you have (for the most part) put the en2re Java program in a single method called main. The main method is special only in that it is the entry point when you start a Java program. Wri2ng large programs in this manner is imprac2cal for a number of reasons. CS 160, Fall Semester 2014 2 Methods Wri2ng monolithic programs in the main method is too complex and hard to understand. Instead programmers split programs into many methods, each of which is simple to understand. A common guideline is that the lis2ng of a method should fit (approximately) on one page. Each method has its own set of local variables, more details on data in a minute. Mysteries Revealed public class Temperature { public static void main(string[] args) { // your code here In our recitations and assignments, you define classes (e.g. P1, R1). You also define a method called main that takes an array of Strings as its parameters CS 160, Fall Semester 2014 3 CS 160, Fall Semester 2014 4 1

Method Types When you use a method you "invoke" or "call" it from another method. Two kinds of Java methods Perform some action and return a single item Perform some and return nothing The method main is a void method Invoked by the system, not the application Does not return anything Calling Methods Calling a method that returns an item For void method, invoke using object name: object.method(); When method returns a value: int value = object.method(); Use the variable value anywhere any other literal or variable value can be used Return values can be of any data type: Primitive types, objects, collections CS 160, Fall Semester 2014 5 CS 160, Fall Semester 2014 6 Defining void Methods Consider method to print something, does not require any data: public void printmethod() System.out.println( Student Name: ); System.out.println( Student EID: ); Method definitions reside in class definition Can be called only on objects of that class Method Declarations public methods can be called from inside or outside the class private methods can be called only from inside the class Data type specifies return type, void means no return value Heading includes parameters in ( ) Body enclosed in braces { CS 160, Fall Semester 2014 7 CS 160, Fall Semester 2014 8 2

Return Values Local Variables Consider method getmonthsinyear( ) public int getmonthsinyear() { int monthsinyear = 12; return monthsinyear; Heading declares type of return value Last statement executed is return Parameter list is empty CS 160, Fall Semester 2014 9 Variables declared inside a method are called local variables May be used only inside the method, i.e. they are valid only in the scope of the method All variables declared in method main are local to main Local variables having the same name and declared in different methods are actually different variables! CS 160, Fall Semester 2014 10 Local Example public double sin(double angle) { double value = Math.sin(angle); return value; public double cos(double angle) { double value = Math.cos(angle); return value; CS 160, Fall Semester 2014 11 Blocks Recall compound statements Enclosed in braces { When you declare a variable within a compound statement The compound statement is called a block The scope of the variable is from its declaration to the end of the block Variables declared outside the block are usable outside and inside the block CS 160, Fall Semester 2014 12 3

Passing Parameters Method declaration must include a list of parameters and their types public double sin(double angle) { return Math.sin(angle); Empty list means no parameters Parameters are separated by commas Note the declaration Method Parameters public int computeinterest(double rate) The formal parameter or argument is rate Calling the method double interest = obj.computeinterest(5.9); The actual parameter is 5.9 CS 160, Fall Semester 2014 13 CS 160, Fall Semester 2014 14 Primitive Parameters Parameter names are local to the method When method invoked Each parameter initialized to value in corresponding actual parameter Primitive actual parameter cannot be altered by invocation of the method Automatic type conversion performed byte -> short -> int -> long -> float -> double Method Examples public double sin(double angle) public double cos(double angle) public char charat(int index) public int indexof(char c) public int minimum(int i, int j) public String tolower(string s) public int[] getarray() CS 160, Fall Semester 2014 15 CS 160, Fall Semester 2014 16 4

public and private public Can access the class, method, or data by name outside defining class private Can access the class, method, or data by name only inside defining class Classes generally specified as public Instance variables usually are private Methods can be public or private CS 160, Fall Semester 2014 17 Pre-condition Comment Precondition comment States conditions that must be true before method is invoked Example double squareroot(double value) { // Parameter value must be > 0 assert (value >0); CS 160, Fall Semester 2014 18 Post-condition Comment Postcondition comment Tells what will be true after method executed Example double squareroot(double value) { root = // Return value is the positive // square root of the value assert(abs(root*root-value)<epsilon); Objects and classes A class is a blueprint for objects: String class provides an abstraction Objects of this class can be instantiated e.g. String firstname = new String(); firstname is an object (instance) of class String firstname is used to invoke methods in class You can define your own classes with Data (e.g., internal private data) Methods CS 160, Fall Semester 2014 19 CS 160, Fall Semester 2014 20 5

Accessors and Mutators When instance variables are private, class must provide methods to access them: Typically named getsomevalue Referred to as an accessor (getter) method Must also provide methods to change the values of the private instance variable Typically named setsomevalue Referred to as a mutator (setter) method Methods Calling Methods A method body may call any other method If the method is within the same class Need not use the class prefix of object that is being called this keyword is assumed, which is shorthand for the class we re currently in CS 160, Fall Semester 2014 21 CS 160, Fall Semester 2014 22 Instance Data Local data resides in a method, class data resides in the class Data defined in the class can be of two types: Data may belong to the class (and will take the same value for all the objects) Data may belong to the object (and can take different values for each instance) Instance Data: Example public class P1 { public int int0; private double real0; int0 visible outside of class, real0 is not, it is private to to the class and can only be accessed from within the class CS 160, Fall Semester 2014 23 CS 160, Fall Semester 2014 24 6

Instance Methods Nota2on: objectname.method() Must be called on an object instan2ated (or created) from a class Most objects are instan2ated with the new keyword: String word = new String( Whatever ); For example, calling word.length() requires an object of type String called word The length() method accesses the data for the specific instance it is called on public sta2c void main Remember that magic incanta2on at the start of your program? main is the name of your method The main method is called by the OS at program startup. void says that the main func2on does not return a value What would the OS do with a return value? sta.c will be explained later public allows access to main outside the class Again the OS needs this access to start the program CS 160, Fall Semester 2014 25 CS 160, Fall Semester 2014 26 Communica2on between calling and called methods Method parameters: Methods define a list of formal parameters to state what must be provided by the calling method. public String reversecase(string s1) Indicates the calling program must specify or pass in a String public int returnrandom() Empty parentheses indicate the calling program specifies no parameters CS 160, Fall Semester 2014 27 Communica2on between calling and called methods Method return type and value: Can return void (e.g. nothing), or can return a type (e.g. int, double, char, String, ) If a value is returned, there must be a return statement in the method body There must be a return for each possible path through the code or compiler will complain Not limited to returning one primi2ve, could be a collec2on or object with lots of data Return type must match assignment in calling method CS 160, Fall Semester 2014 28 7

Communica2on between calling and called methods public String reversecase(string s1) public int returnrandom() Calling method: Supplies arguments that must match the type of the parameters in the method declara2on Uses the return value by storing it, prin2ng it, or using it for a calcula2on, must match type. System.out.print(reverseCase(str)); int random = returnrandom(); CS 160, Fall Semester 2014 29 Cau2on: Pass by value What do you expect this to print? public class PassByValue { public sta.c void main(string[] args) { int number = 100; increment(number); System.out.println( Number: + number; public sta.c void increment(int n) { n++; The value of the argument is copied, so no change to number! CS 160, Fall Semester 2014 30 Incorrect Swapping public class Swapper { public sta.c void main(string[] args) { String s1 = "Mar.n"; String s2 = "Scorcese"; swap(s1, s2); System.out.println( main: AGer swap, s1=" +s1+ " and s2=" +s2); public sta.c void swap(string x, String y) { System.out.println( swap: Before swap, x= +x+ and y= +y); String temp = x; x = y; y = temp; System.out.println( swap: AGer swap, x=" +x+ " and y=" +y); Nothing gets swapped! CS 160, Fall Semester 2014 31 Methods inside a class Order of wri2ng methods is arbitrary Generally constructors are wrieen first What if two methods need to share data? One subtask reads input and creates a string of words separated by white space Another subtask checks each word in the string one at a 2me CS 160, Fall Semester 2014 32 8

First Solu2on Called method returns a value (data) Calling method uses the value (data) Example: public sta.c void main(string[] args) { String wordlist = readinput(); processwords(wordlist); Second Solu2on Use instance variables Define String wordlist; as an instance variable in the class Any method of a class can access its variables readinput() can create and write the string processwords() can access (read) the same string Of course neither method can be sta.c since the instance variable is not sta2c! CS 160, Fall Semester 2014 33 CS 160, Fall Semester 2014 34 Encapsulation Consider example of driving a car We see and use break pedal, accelerator pedal, steering wheel know what they do We do not see mechanical details of how they do their jobs Encapsulation divides class definition into Class interface Class implementation Interface/Implementation A class interface Tells what the class does Gives headings for public methods and comments about them A class implementation Contains private variables Includes definitions of public and private methods 9

Encapsulation/Interfaces Interfaces A well encapsulated class definition: Programmer who uses the class Class definition has comments on how to use class All instance variables in the class declared as private. Provide public accessor methods to retrieve data Provide public mutator methods to manipulating data Add comments before each public method heading that fully specifies how to use method. Write comments within class definition to describe implementation details. Hide everything else: data structures, helper methods, other implementation details. Interface Example public interface Trigonometry { public double sin(double angle); public double cos(double angle); public double tan(double angle); public class Math implements Trigonometry { public double sin(double angle) { code public double cos(double angle) { code public double tan(double angle) { code Trigonometry trig = new Math(); 10