Methods Coding in Java Copyright © 1997 - 2009 Curt Hill.

Slides:



Advertisements
Similar presentations
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Advertisements

 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Introduction to Methods
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Programming Writing Java Beginning Java Programs.
Comments are for people Header comments supply basic information about the artifact.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
COSC 1P02 Introduction to Computer Science 3.1 Cosc 1P02 Week 3 Lecture slides Birthdays are good for you. Statistics show that the people who have the.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Copyright © Curt Hill Turtles The beginning of media computation.
ECE122 Feb. 22, Any question on Vehicle sample code?
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Programming Writing Java Beginning Java Programs.
Copyright Curt Hill Variables What are they? Why do we need them?
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Classes - Intermediate
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
Copyright © Curt Hill Flow of Control A Quick Overview.
Copyright © Curt Hill Simple I/O Input and Output using the System and Scanner Objects.
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
The for Statement A most versatile loop
Information and Computer Sciences University of Hawaii, Manoa
The Second C++ Program Variables, Types, I/O Animation!
Functions + Overloading + Scope
Getting and displaying
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
3 Introduction to Classes and Objects.
A Review or Brief Introduction
More methods, more capabilities
COMP 170 – Introduction to Object Oriented Programming
Lecture 5: Some more Java!
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
Chapter 3: Using Methods, Classes, and Objects
Selenium WebDriver Web Test Tool Training
University of Central Florida COP 3330 Object Oriented Programming
Lecture 14 Writing Classes part 2 Richard Gesick.
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.
Part II The Switch Statement
Methods Additional Topics
Type Conversion, Constants, and the String Object
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 6 Methods: A Deeper Look
Variables ICS2O.
Group Status Project Status.
IFS410 Advanced Analysis and Design
Defining methods and more arrays
Compound Statements A Quick Overview
Other displays Saving Arrays Using fors to process
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
Methods Again Parameter Passage
Anatomy of a Java Program
The Java switch Statement
Object Oriented Programming in java
Defining Classes and Methods
Classes, Objects and Methods
Corresponds with Chapter 5
The beginning of media computation Followed by a demo
Methods Scope How are names handled?
Presentation transcript:

Methods Coding in Java Copyright © 1997 - 2009 Curt Hill

What is a Method? A chunk of executable code It always has four things: A return type A name A parameter list A compound statement It may optionally have: Visibility Static or other attributes The main method is an example Copyright © 1997 - 2009 Curt Hill

Main method Our main method is an example public static void main (String [] a) {…} public is visibility void means that no value is returned main is the method name (…) contains parameters {…} contains declarations and executables Copyright © 1997 - 2009 Curt Hill

The Return Type May be any of the primitives May be any of the objects int, double, char, boolean May be any of the objects Turtle, World, Color, even arrays May also be void Reserved word indicating no value is returned Copyright © 1997 - 2009 Curt Hill

The Name Any Java name The convention is that it starts with a lower case letter Each letter that starts a word is then capitalized Examples: forward moveTo setPenColor This is just a convention, but a good thing for you to follow Copyright © 1997 - 2009 Curt Hill

The Parameter List A list of values that needs to be made available to the method The parameter list is enclosed in parentheses The parentheses are always present, even if there are no parameters The parameters are denoted by a type followed by its local name Copyright © 1997 - 2009 Curt Hill

Parameters A method may have multiple parameters Each has same form: type localname These pairs are separated by commas A Turtle method signature: void forward(int steps) { … } Copyright © 1997 - 2009 Curt Hill

The Compound Statement The body of the method is a compound statement Starts with a brace { One or more statements Ends with other brace } Every opening brace { must be matched by a closing brace } The parameter is part of the compound statement for scope considerations Copyright © 1997 - 2009 Curt Hill

Method header That part of the method excluding the compound statement is called the method header This is the part usually shown in documentation Such as the doc directory within the bookClasses directory Copyright © 1997 - 2009 Curt Hill

Calling a Method Multiple parameters are separated by commas The general form is: variable.method(parm list) This may be a stand-alone statement yertle.forward(150); It may be part of a statement: x = y + Math.sqrt(3.5); Multiple parameters are separated by commas The names do not have to match Copyright © 1997 - 2009 Curt Hill

The end of a method There are two ends to consider The syntax The execution As far as syntax is concerned a method ends when we find the closing brace of its compound statement In this sense a method is only processed once Copyright © 1997 - 2009 Curt Hill

Ending Execution A method ends when one of two things happens: A return is executed The last line of the method is executed This only works on void methods Return is the mechanism for identifying the value With void functions there is no value to identify Copyright © 1997 - 2009 Curt Hill

The return statement Has two effects Ends the function and returns to calling statement Determines the value that needs to be returned Form is: return expression; Expression should match return type Copyright © 1997 - 2009 Curt Hill

Identifying Parameters The parameter described in the method header is called the formal parameter The parameter used in the call is the actual parameter The names of the two do not need to match Copyright © 1997 - 2009 Curt Hill

Formals and Actuals A formal parameter is i void print(int i); Three actual parameters int j=5,k=2; … System.out.print(j); System.out.print(12); System.out.print(k*-j+1); Formals and actuals should match in type Copyright © 1997 - 2009 Curt Hill

Example Method static void triangle( Turtle t){ t.forward(50); t.turn(120); } Copyright © 1997 - 2009 Curt Hill

Called by public static void main( String [] a){ World w = new World(400,240); Turtle yertle = new Turtle(w); yertle.setPenWidth(3); triangle(yertle); Turtle sam = new Turtle(100, 100, w); sam.setPenWidth(4); triangle(sam); } Copyright © 1997 - 2009 Curt Hill

Gives Results Copyright © 1997 - 2009 Curt Hill

Example commentary The name of the formal and actual parameters did not have to match This allows the method to make any turtle draw, not just one This or any method may be called as many times as desired With the same or different parameters Copyright © 1997 - 2009 Curt Hill

Why is method static? static is a Java keyword For methods it means that the method has no access to class instance data It must have access to local data Since they have no access to class data they may be called before the constructor They may only use their parameters and local data Copyright © 1997 - 2009 Curt Hill

Static again The main function is a static function It may actually instantiate a class of the type to which it belongs A static method may only call other static methods unless it instantiates an instance of its own class Thus triangle needed to be static Copyright © 1997 - 2009 Curt Hill

Why use static? Suppose: public class Demo{ public static void main (String s[]){ … } } To use a non-static method we would need: Demo t = new Demo(); Copyright © 1997 - 2009 Curt Hill

The Non-static equivalent We can do this without static methods but it is slightly more work Consider the next three screens Copyright © 1997 - 2009 Curt Hill

Notice class name public class TurtleMethod2 { /** * Non-static methods */ void triangle(Turtle t){ t.forward(100); t.turn(120); } Copyright © 1997 - 2009 Curt Hill

New main method public static void main(String[] args) { TurtleMethod2 item = new TurtleMethod2(); World w = new World(850,500); Turtle yertle = new Turtle(w); Turtle sam = new Turtle(700,450,w); yertle.setPenWidth(3); item.triangle(yertle); sam.setPenWidth(4); item.triangle(sam); } Copyright © 1997 - 2009 Curt Hill

Commentary The result is the same What are the differences? Leave static off of triangle method Create a TurtleMethod2 item using new Prefix triangle with the TurtleMethod2 object, which is named item Copyright © 1997 - 2009 Curt Hill

Parameters Again The method needs some refinement It always draws the same size triangle It becomes more helpful if the length of a side can be changed This is a second parameter Copyright © 1997 - 2009 Curt Hill

Second Example static void triangle( Turtle t, int len){ t.forward(len); t.turn(120); } Copyright © 1997 - 2009 Curt Hill

Called by public static void main( String [] a){ World w = new World(400,240); Turtle yertle = new Turtle(w); yertle.setPenWidth(3); triangle(yertle,80); Turtle sam = new Turtle(100,100,w); sam.setPenWidth(4); triangle(sam,40); } Copyright © 1997 - 2009 Curt Hill

Gives Results Copyright © 1997 - 2009 Curt Hill

Method Calls Why does triangle not have an object in front? What is difference between: yertle.forward(20); triangle(yertle,50); We do not need the object for triangle because the object is the program If we were in Turtle we could just say forward without the prefixed Turtle name Copyright © 1997 - 2009 Curt Hill

Method Execution When a method call is encountered what happens? The actual parameters are evaluated The values are connected to the formal parameters The calling method is suspended and the method is started All local variables are created The method is executed The return ends the method choosing the returned value The caller is activated with the returned value Copyright © 1997 - 2009 Curt Hill

Name Overloading In many languages such as C, Pascal, VB a function is defined by one thing only: the function name C++ introduced function name overloading It determines the function to use by examining the signature Java does the same Copyright © 1997 - 2009 Curt Hill

Method Signatures A method is uniquely determined by two things: the name the parameter list The contribution of the parameter list does not include the parameter names, only number, type and order These are collectively called the signature Two signatures within a class may not be the same Copyright © 1997 - 2009 Curt Hill

Multiple Triangles There is no conflict with having both triangle methods in one program The compiler can tell the difference because one has two parameters and the other one Copyright © 1997 - 2009 Curt Hill

Why use methods? Two good reasons Several others besides Allows one instance of identical or similar code We may now draw a triangle as easily as we could draw a line before With any size, any turtle Allows simplification of main program Five or more statements replaced by one Copyright © 1997 - 2009 Curt Hill

Finally There is plenty more to know This will come in several subsequent presentations We should do a demo Copyright © 1997 - 2009 Curt Hill