Comp1004: Building Better Objects I Methods. Coming up Methods and Parameters – Why Parameterise? – Call by value, call by reference Return Types – Methods.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Announcements  If you need more review of Java…  I have lots of good resources – talk to me  Use “Additional Help” link on webpage  Weekly assignments.
Methods F Hello World! F Java program compilation F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters by value F Overloading.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
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.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
Methods.
Comp1004: Programming in Java I Variables - Primitives, Objects and Scope.
OOP Basics Classes & Methods (c) IDMS/SQL News
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Comp1004: Building Better Objects II Encapsulation and Constructors.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
Eastside Robotics Alliance / Newport Robotics Group 1 T/Th, 6:30 – 8:30 PM Big Picture School Day 3 · 10/9/2014.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Content Programming Overview The JVM A brief look at Structure – Class – Method – Statement Magic incantations – main() – output Coding a Dog Programming.
Chapter VII: Arrays.
Content Programming Overview The JVM A brief look at Structure
Coming up Constructors Overloading With one parameter
Lecture 10: More on Methods and Scope
Chapter 5 Function Basics
CompSci 230 Software Construction
Templates.
Advanced Programming in Java
Advanced Programming in Java
CSC240 Computer Science III
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Lecture 11 C Parameters Richard Gesick.
Interfaces and Constructors
Encapsulation and Constructors
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Questions? Math Class Wrapper Classes Writing / Testing Methods.
Method Overloading in JAVA
Chapter 4 Topics: class declarations method declarations
Chapter 6 Methods.
Variables, Types, Operations on Numbers
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Building Java Programs
Building Java Programs
Building Java Programs
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
Introduction to Object-Oriented Programming
Lecture 11 Parameters CSE /26/2018.
CMSC 202 Lesson 6 Functions II.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
CISC101 Reminders Assignment 3 due today.
Methods/Functions.
CMPE212 – Reminders Assignment 2 due next Friday.
Parameters, Overloading Methods, and Random Garbage
ITM 352 Functions.
Corresponds with Chapter 5
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Comp1004: Building Better Objects I Methods

Coming up Methods and Parameters – Why Parameterise? – Call by value, call by reference Return Types – Methods as a Function Overloading

Methods and Parameters

Why Parameterise? public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdrawFiver(); myAccountObject.withdrawTenner(); } public void withdrawFiver(){ balance = balance - 5; } public void withdrawTenner(){ int tenner = 10; balance = balance – 10; } These two methods do almost the same thing. It is wasteful (inelegant?) to write them twice

Why Parameterise? public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5); myAccountObject.withdraw(10); } public void withdraw(int amount){ balance = balance - amount; } They can be replaced by a single method that behaves differently depending on what values are passed to it

Why Parameterise? public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5); myAccountObject.withdraw(10); } public void withdraw(int amount){ balance = balance - amount; } Values received by a method are called parameters. Within the method they can be used like any other local variable Values passed into a method are called arguments

Why Parameterise? public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5); myAccountObject.withdraw(10); myAccountObject.withdraw(“ten pounds”); myAccountObject.withdraw(‘5’); } public void withdraw(int amount){ balance = balance - amount; } Each parameter is typed. You will get a compiler error if you try and pass a method a value of the wrong type

Why Parameterise? public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5); myAccountObject.withdraw(10); myAccountObject.withdraw(“ten pounds”); myAccountObject.withdraw(‘5’); } public void withdraw(int amount){ balance = balance - amount; } Each parameter is typed. You will get a compiler error if you try and pass a method a value of the wrong type “ten pounds” is of type String ‘5’ is of type char So these lines will not compile

Why Parameterise? public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5, “Soton Uni Shop”); myAccountObject.withdraw(10, “ATM”); } public void withdraw(int amount, String desc){ balance = balance - amount; System.out.print(“Withdrew £”); System.out.print(amount); System.out.print(“ via ”); System.out.println(desc); } Methods can take multiple parameters Each is separated by a comma, and has its own name and type

Parameters, Primitives and Objects b Elephant a int int a; a = 10; Elephant b; b = new Elephant();

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } Assuming that isHungry returns true or false depending on whether the elephant has been fed, and that the zoo is open and has food - what will be printed here?

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } Visitors is a primitive, so when it is sent to a method it is pass by value

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } Visitors is a primitive, so when it is sent to a method it is pass by value visitors int

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } Visitors is a primitive, so when it is sent to a method it is pass by value visitors int v

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } Visitors is a primitive, so when it is sent to a method it is pass by value visitors int v

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } Visitors is a primitive, so when it is sent to a method it is pass by value visitors int

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } Visitors is a primitive, so when it is sent to a method it is pass by value visitors int So this line will print “0”

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } elephant is an object reference, so when it is sent to a method it is pass by reference

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } elephant is an object reference, so when it is sent to a method it is pass by reference elephant Elephant

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } elephant is an object reference, so when it is sent to a method it is pass by reference elephant Elephant e

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } elephant is an object reference, so when it is sent to a method it is pass by reference elephant Elephant e

Parameters, Primitives and Objects public class Zoo{ public static void main(String[] args){ int visitors = 0; Elephant elephant = new Elephant(); incVisitors(visitors); feedElephant(elephant); System.out.println(visitors); System.out.println(elephant.isHungry()); } public void incVisitors(int v) { if(zooIsOpen()) v++; } public void feedElephant(Elephant e) { if(zooHasFood()) e.feed(); } //some code omitted } elephant is an object reference, so when it is sent to a method it is pass by reference elephant Elephant So this line will print “false”

Sometimes (often), we (everyone) gets lazy and says we pass a method an object. This really means we pass that object’s reference. Just so you know

Return Types

Methods as Functions One way to think about methods is like mathematical functions Function InputsOutput

Return types public class CashRegister{ public static void main(String[] args){ CashRegister reg = new CashRegister(); float p1 = 10.0; reg.calcVAT(p1); System.out.println(p1); } public void calcVAT(float price) { price = price * 1.2; } What will happen?

Return types public class CashRegister{ public static void main(String[] args){ CashRegister reg = new CashRegister(); float p1 = 10.0; reg.calcVAT(p1); System.out.println(p1); } public void calcVAT(float price) { price = price * 1.2; } Because p1 is a float (a primitive) it is pass by value. So this line will not increase the value of p1. The program will print 10.0 on the screen. What will happen?

Return types public class CashRegister{ public static void main(String[] args){ CashRegister reg = new CashRegister(); float p1 = 10.0; p1 = reg.calcVAT(p1); System.out.println(p1); } public float calcVAT(float price) { return price * 1.2; } Instead we can specify a return type And use the return keyword to pass back a value to wherever the method was called

Return types public class CashRegister{ public static void main(String[] args){ CashRegister reg = new CashRegister(); float p1 = 10.0; p1 = reg.calcVAT(p1); System.out.println(p1); } public float calcVAT(float price) { return price * 1.2; } Instead we can specify a return type And use the return keyword to pass back a value to wherever the method was called Whatever called the method can then assign the return type to a variable (or do anything else with it!)

Can I return more than one thing? public int getAgeAndName(){ return age, name; } This is not legal Java Like a mathematical function you can only return one thing So there can only be one return type But....

Collections Later in the course we deal with collections (implemented as classes and objects) You can put many objects or primitives into collections So you could pass or return a collection from a method in order to process many values at once

Overloading

public class CashRegister{ public static void main(String[] args){ CashRegister reg = new CashRegister(); float p1 = 10.0; p1 = reg.calcVAT(p1); System.out.println(p1); } public float calcVAT(float price) { return price * 1.2; } Variations on a Method What if we wanted to pass the VAT rate as one of the parameters?

public class CashRegister{ public static void main(String[] args){ CashRegister reg = new CashRegister(); float p1 = 10.0; p1 = reg.calcVAT(p1); p1 = reg.calcVAT(p1, 0.175); System.out.println(p1); } public float calcVAT(float price) { return price * 1.2; } public float calcVAT(float price, float rate) { return price * (1.0 + rate); } Variations on a Method What if we wanted to pass the VAT rate as one of the parameters? We could add it as a second parameter. N.B. that the two methods have the same name

This is called Overloading A method is recognised by its signature – (its name, parameters and the order of parameters) When overloading each method must have a unique signature – Remember that the return type is NOT part of the signature – float calcVAT(float price) – float calcVAT(float price, float rate) OK – int calcVAT(float price, char band) OK

This is called Overloading A method is recognised by its signature – (its name, parameters and the order of parameters) When overloading each method must have a unique signature – Remember that the return type is NOT part of the signature – float calcVAT(float price) – float calcVAT(float price, float rate) OK – int calcVAT(float price, char band) OK – int calcVAT(float price) not OK clashes

public class CashRegister{ public static void main(String[] args){ CashRegister reg = new CashRegister(); float p1 = 10.0; p1 = reg.calcVAT(p1); p1 = reg.calcVAT(p1, 0.175); System.out.println(p1); } public float calcVAT(float price) { return price * 1.2; } public float calcVAT(float price, float rate) { return price * (1.0 + rate); } Variations on a Method When a method is called Java invokes the method with the matching signature Overloading

Summary Methods and Parameters – Why Parameterise? – Call by value, call by reference Return Types – Methods as a Function Overloading