CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Similar documents
CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Binghamton University. CS-140 Fall Data Types in Java

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

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

Introduction to Programming (Java) 4/12

Selected Questions from by Nageshwara Rao

CS 455 Midterm Exam 1 Fall 2017 [Bono] Thursday, Sep. 28, 2017

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Manual for Basic Java

Programming Language Concepts: Lecture 2

Chapter 6 Introduction to Defining Classes

For this section, we will implement a class with only non-static features, that represents a rectangle

Using Objects. a first example of an object classes and objects in Java

Methods Summer 2010 Margaret Reid-Miller

Express Yourself. Writing Your Own Classes

Java Primer 1: Types, Classes and Operators

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

CS 231 Data Structures and Algorithms, Fall 2016

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

Programming Language Concepts: Lecture 2

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 2, Name:

3 ADT Implementation in Java

Preview from Notesale.co.uk Page 9 of 108

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Midterms Save the Dates!

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

Lecture 7: Classes and Objects CS2301

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

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.

Chapter 4 Defining Classes I

A Formal Presentation On Writing Classes With Rules and Examples CSC 123 Fall 2018 Howard Rosenthal

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

BM214E Object Oriented Programming Lecture 8

Intro to Computer Science II

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Programming II (CS300)

CSCI 161 Introduction to Computer Science

Array. Prepared By - Rifat Shahriyar

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

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

Pace University. Fundamental Concepts of CS121 1

Class, Variable, Constructor, Object, Method Questions

- Thus there is a String class (a large class)

Implementing Classes

Implementing Classes (P1 2006/2007)

Methods and Data (Savitch, Chapter 5)

52 Franck van Breugel and Hamzeh Roumani

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

! Rest of Chap 2 ! 2.3-4, ! Rest of Chap 4 ! ! Things that do not vary. ! unlike variables. ! will never change. !

A Founda4on for Programming

CS-202 Introduction to Object Oriented Programming

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

CS 1302 Chapter 9 (Review) Object & Classes

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

ITI Introduction to Computing II

Programming Language Concepts: Lecture 1

Object Oriented Programming 2015/16. Final Exam June 28, 2016

3.1 Class Declaration

Review: Array Initializer Lists

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

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

Comments are almost like C++

Unit 4: Classes and Objects Notes

Computer Science II Data Structures

ITI Introduction to Computing II

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

Subclassing for ADTs Implementation

Lecture Notes Chapter #9_b Inheritance & Polymorphism

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

Programming by Delegation

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Introduction to Programming Using Java (98-388)

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

BM214E Object Oriented Programming Lecture 4

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

Practice exam for CMSC131-04, Fall 2017

Inheritance and Polymorphism

Programming with Java

Implementing non-static features

Mutating Object State and Implementing Equality

9 Working with the Java Class Library

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

CS 61C: Great Ideas in Computer Architecture Introduction to C

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

More non-primitive types Lesson 06

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

Object Oriented Modeling

Lecture 5: Methods CS2301

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Transcription:

Methods There s a method in my madness. Sect. 3.3, 8.2 1

Example Class: Car How Cars are Described Make Model Year Color Owner Location Mileage Actions that can be applied to cars Create a new car Transfer ownership Move to a new location Repaint Delete a car 2

What s in a class? Fields The data used to describe an object in the class Methods The functions used to manipulate an object in the class 3

Terminology Method: A function in a class definition which implements an action that can be performed on an object Receiver: The object from which the method was invoked most typically, the object which the method acts on. Methods have an implicit parameter of this which refers to the receiver object. Argument: data passed to a method. Arguments are from the invocation point of view, as compared to parameters. Parameter: data passed to a method. Parameters are from the method s point of view, as compared to arguments 4

Method Syntax modifiers returntype name (parameters) throws { body Sect. 3.2, 3.3 modifiers : public private static also: protected abstract final synchronize native strictfp returntype : Any primitive or reference type or void name : Any valid identifier 5

Parameters Comma separated list of things that look like variable declarations Each parameter is a positional place-holders to hold the values that are to be passed a method to allow it to complete its action The last parameter in the list may specify a variable length list of values. If so, it must be specified as type name where name is interpreted as an array within the method. 6

Example Method Headers public static void main(string[ ] args) { int factorial(int n) { public void println(string x) { Modifiers Return Type name Parameters public GridLayout(int rows, int cols, int hgap, int vgap) { public static int sum(int numbers) 7

Method Modifiers static vs. Dynamic : See next slides public vs. protected vs. private vs. package-private public method can be used by all java code protected method is visible in super-classes and in the package package-private method is visible only to java code in the package This is the default if nothing else is specified private method is visible only within the class abstract, final,. we ll talk about later 8

static methods behave like C class XmpStat { static int add3(int x) { return x+3; class Tester { public static void main() { System.out.println( 20+3= + XmpStat.add3(20)); 9

Why static (class) methods? Enable main before any objects are available Enable functions methods which don t act on objects Alternative meaningless empty object which requires creation Enable factory methods methods which create new objects, but are not constructors 10

Instance vs. Class Methods If a method is declared as static, it is a class method Invoked like a function not as an action on an object Invocation prefixed by class name and dot Class methods do not have a receiver object Class methods do not have a this implicit parameter Constructors are invoked like a class method Most methods are instance methods methods which are invoked as actions on specific objects Note: Constructors are more like instance methods, even though they are not invoked like instance methods 11

Instance Method Invocation Instance methods are invoked by specifying an action to occur to an object DollarsAndCents mymoney = new DollarsAndCents(12,50); mymoney.upordown(1.05); Reference to an object in the DollarsAndCents class Action: Method from the DollarsAndCents class Argument to be passed to the upordown method 12

Instance Method Implicit this Parameter The object that receives the action ( the object which the action is performed on) is called the receiver object. The receiver object is implicitly placed in the parameter list of the method, as if (but not actually) you had specified: class Rectangle { void translate(int dx, int dy) { is very similar too static void strans(rectangle workon, int dx, int dy) { 13

instance vs. static method invocation Rectangle rect = new Rectangle(10,20,10,40); rect.translate(-5,10); // invoke instance method // implicit : rect passed in as this parameter Rectangle.strans(rect,+5,-10); // invoke class method // explicit : rect passed in as workon parameter 14

Return Type Required for all methods EXCEPT constructors Use void to indicate method does not return anything For constructors, return type is implicit A reference to the object of the current class 15

Constructors Invoked as: new class(constructor_parameters); class Class of the newly created object constructor_parameters Any parameters required to create the object Constructor method name must match class name! Java creates a new object All fields are initialized to zero or empty or null There is an implicit this argument passed to the method points to the new object with null fields Constructor initializes field values Constructor implicitly returns a reference to this 16

Arguments The positional list of values or references passed in to a method (to be kept in a parameter) An argument may be an expression that evaluates to a value or a reference System.out.println("Hello"); factorial(10); panel.setlayout(new GridLayout(2, 2, 5, 5)); Arguments 17

Rectangle Class Example Rectangles expressed as (left x, top y, width, height) Rectangle rect1 = new Rectangle(70,90,100,150); translate means move a shape without changing it rect1.translate(100, 80); moves rect1 to (170, 170, 100, 150) 18

Rectangle example continued public static void main(string[ ] args) { Rectangle rect1 = new Rectangle(70,90,100,150); Rectangle rect2 = new Rectangle(70,180,200,50); rect1.translate(100, 80); There is only one copy of the code for the method translate, not one copy for each object How is that translate moves rect1 and not rect2? The code of translate has to receive a reference to the object it will read information from or modify See class web page example FirstGUI 19

Note: No Code in Objects In section 2.3 of the text, there are diagrams like: Despite these pictures, there is no actual CODE stored in the object! The object ONLY contains the values of the fields for that object The code is stored in memory only once for the entire class 20

Method Signatures Java allows multiple definitions of the same method name! As long as the parameters types are different! Method signature includes: name and parameter types When a method is invoked, Java looks at the arguments to determine the signature, and invokes the method with that signature! Often multiple constructors with different signatures Sometimes used for instance or class methods as well 21

Example: public class Account { double balance; public Account(double initbalance) { this.balance=initbalance; public Account() { this.balance=0.0; public static void main(string args[]) { my acct1=new Account(120.00); my acct2 = new Account(); 22

Method Invocation Internals When a method is invoked, the JVM: Creates an activation record keeps track of info about the current method invocation Saves where the method was invoked from Evaluates argument expressions, and copies the results into the activation record including receiver this Reserves space in the activation record for local variables Executes the method When a return statement is encountered, saves the return value Goes back to the caller of the method Deletes the activation record 23

Activation Record Implications Parameters are copied, not passed by reference However, if a reference is copied, you can change the referenced object! New local variables with each invocation No access to local variables before or after invocation But objects referenced can be accessed after invocation as long as you still have a handle. 24

Activation Record Example public static void main(string[ ] args) { Rectangle rect1 = new Rectangle(70,90,100,150); Rectangle rect2 = new Rectangle(70,180,200,50); rect1.translate(100, 80); 25

Rectangle Class public class Rectangle { int leftx; int topy; int w; int h; public Rectangle(int lx, int ty, int wid, int hgt) { this.leftx=lx; this.topy=ty; this.w=wid; this.h=hgt; void translate(int dx,int dy) { this.leftx+=dx; this.topy+=dy; 26

Rectangle Class public class Rectangle { int leftx; int topy; int w; int h; If field names are different than variable names, Java assumes this. public Rectangle(int lx, int ty, int wid, int hgt) { this.leftx=lx; this.topy=ty; this.w=wid; this.h=hgt; void translate(int dx,int dy) { this.leftx+=dx; this.topy+=dy; 27

Rectangle Class public class Rectangle { int leftx; int topy; int w; int h; If field names are different than variable names, Java assumes this. public Rectangle(int lx, int ty, int wid, int hgt) { leftx=lx; topy=ty; w=wid; h=hgt; void translate(int dx,int dy) { leftx+=dx; topy+=dy; 28

main Binghamton Memory (at start of main) public static void main(string[ ] args) { Rectangle rect1 = new Rectangle(70,90,100,150); Rectangle rect2 = new Rectangle(70,180,200,50); rect1.translate(100, 80); activation records Java Bytecode rect2 rect1 args Next, new will create a rectangle object, and invoke the Rectangle creator 29

main Rectangle.Rectangle Binghamton Memory (at start of rect1 constructor) Activation Records this lx=70 ty=90 wid=100 hgt=150 rect2 rect1 args Rectangle leftx 0 topy 0 w 0 h 0 public class Rectangle { Next, the Rectangle creator returns Java Bytecode int leftx; int topy; int w; int h; 30

main Binghamton Memory (after rect1 constructor) Java Bytecode Call Stack rect2 rect1 args Rectangle leftx 70 topy 90 w 100 h 150 public Rectangle(int lx, int ty, int wid, int hgt) { leftx=lx; topy=ty; w=wid; h=hgt; Next, rect2 is created similarly, and then the translate method is invoked 31

main Rectangle.translate Binghamton Memory (at start of translate method) Java Bytecode Call Stack this dx=100 dy=80 rect2 rect1 args Rectangle leftx 70 topy 90 w 100 public static void main(string[ ] args) { Rectangle rect1 = new Rectangle(70,90,100,150); Rectangle rect2 = new Rectangle(70,180,200,50); rect1.translate(100, 80); h 150 Rectangle leftx 70 topy 180 w 200 h 50 32

Accessor vs. Mutator Methods Sect. 2.5 If a method changes the receiver object field values, it is called a mutator method. For example the translate method in Rectangle changes the value of leftx and topy it is a mutator method If a method does not change the receiver object field values, it is called an accessor method. For example the getwidth method in Rectangle does not change any of the fields in rectangle it is an accessor method. If all methods are accessor methods, the Class is called an immutable class For example the String class is immutable. 33

Example: Immutable String Class Strings are arrays of characters, so index starts at 0 int z = "CS 140".length( ); //gives z the value 6 String str = "CS 140"; // implicit String creation String s1 = str.substring(0, 2); // s1 is CS char ch = str.charat(3); // gives ch the value '1 34

What can we do with Strings? Substring : String substring(int beginindex, int endindex) Replace: String replace(char oldchar, char newchar) Change Case: String tolowercase() Notice, original object is not altered! Strings are immutable. A modified object is returned! 35

Demonstrating Immutable Strings String str = This is a test. ; String str2 = str.replace( t, v ); System.out.println(str); System.out.println(str2); This is a test This is a vesv 36

Equality : boolean equals(object x) str1 str2 str3 str4 String str1= CS 140 ; String str2= CS 140 ; String str3= CS 220 ; String str4 = str1; String value CS 140 String str1.equals(str2)? str1.equals(str3)? str1==str2? str1==str4? value CS 140 String True False False True strx==stry &&!strx.equals(stry)? value CS 220 False 37