Methods and Data (Savitch, Chapter 5)

Similar documents
Methods. Methods. Mysteries Revealed

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

Classes. Classes as Code Libraries. Classes as Data Structures

Defining Classes and Methods

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

5. Defining Classes and Methods

5. Defining Classes and Methods

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

Defining Classes and Methods

Defining Classes and Methods

Chapter 4 Defining Classes I

Defining Classes and Methods

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

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

Introduction to Programming Using Java (98-388)

Defining Classes and Methods

EECS168 Exam 3 Review

Defining Classes and Methods

Chapter 6 Introduction to Defining Classes

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Chapter 4. Defining Classes I

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

Lecture 04 FUNCTIONS AND ARRAYS

by Pearson Education, Inc. All Rights Reserved. 2

Chapter 4: Writing Classes

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

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

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

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

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

Ticket Machine Project(s)

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.

Anatomy of a Class Encapsulation Anatomy of a Method

Programming II (CS300)

Chapter 4. Defining Classes I

Programming II (CS300)

PROGRAMMING FUNDAMENTALS

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

Principles of Object Oriented Programming. Lecture 4

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

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Introduction to Programming (Java) 4/12

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

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

Object-Oriented Programming Concepts

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

( &% class MyClass { }

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

JAVA GUI PROGRAMMING REVISION TOUR III

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

Objects as a programming concept

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

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

JAVA Programming Concepts

CHAPTER 7 OBJECTS AND CLASSES

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Java+- Language Reference Manual

Programming II (CS300)

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

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

Full file at

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

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

Advanced Object Oriented Programming EECS2030Z

Topic 3 Encapsulation - Implementing Classes

Defining Classes and Methods

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Utilities (Part 2) Implementing static features

CHAPTER 7 OBJECTS AND CLASSES

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

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

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005

Object Oriented Programming in C#

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

CS 231 Data Structures and Algorithms, Fall 2016

Lecture 5: Methods CS2301

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object Oriented Programming

Recitation 02/02/07 Defining Classes and Methods. Chapter 4

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

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

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

An overview of Java, Data types and variables

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

Computer Science II (20082) Week 1: Review and Inheritance

Objects and Classes -- Introduction

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

Functions. Lecture 6 COP 3014 Spring February 11, 2018

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Computer Science II (20073) Week 1: Review and Inheritance

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

More About Objects and Methods

More About Objects and Methods. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

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

Transcription:

Methods and Data (Savitch, Chapter 5) TOPICS Invoking Methods Return Values Local Variables Method Parameters Public versus Private 2 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 3 4

Method Types Calling Methods 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 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 5 6 Defining void Methods Method Declarations 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 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 { 7 8

Return Values 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 Local Variables 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! 9 10 Local Example Blocks public double sin(double angle) { double value = Math.sin(angle); return value; public double cos(double angle) { double value = Math.cos(angle); return value; 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 11 12

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 double 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 13 14 Primitive Parameters Method Examples 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 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() 15 16

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 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); 17 18 Post-condition Comment Objects and classes 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); 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 19 20

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 21 22 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 23 24

25 26 public String reversecase(string s1) public int returnrandom() 27 28

public String reversecase(string s1) public int returnrandom() System.out.print(reverseCase(str)); int random = returnrandom(); public class PassByValue { public static void main(string[] args) { int number = 100; increment(number); System.out.println( Number: + number); public static void increment(int n) { n++; 29 30 public class PassByValue { public static void main(string[] args) { int number = 100; number = increment(number); System.out.println( Number: + number); public static int increment(int n) { return ++n; 31 32

33 34 Encapsulation String wordlist; 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 35 36

Interface/Implementation Encapsulation/Interfaces 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 A well encapsulated class definition: Programmer who uses the class 37 38 Interfaces Interface Example 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. 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(); 39 40