Methods. Methods are groups of statements placed together under a single name. All Java applications have a class which includes a main method class MyClass.

Slides:



Advertisements
Similar presentations
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Dialogs. Displaying Text in a Dialog Box Windows and dialog boxes –Up to this our output has been to the screen –Many Java applications use these to display.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Enhancing classes Visibility modifiers and encapsulation revisited
Introduction to Computers and Programming Lecture 3: Variables and Input Professor: Evan Korth New York University.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 10: 1 TEST!!
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Writing Methods. Create the method Methods, like functions, do something They contain the code that performs the job Methods have two parts.
Lecture From Chapter 6 & /8/10 1 Method of Classes.
JOptionPane class. Dialog Boxes A dialog box is a small graphical window that displays a message to the user or requests input. A variety of dialog boxes.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
CS 106 Introduction to Computer Science I 01 / 31 / 2007 Instructor: Michael Eckmann.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 7: Methods & User Input.
Methods We write methods in our programs for many reasons:
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.
Chapter 2 Getting Started with Java. Objectives After you have read and studied this chapter, you should be able to Identify the basic components of Java.
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.
CSI 3125, Preliminaries, page 1 Compiling the Program.
CIS 234: Java Methods Dr. Ralph D. Westfall April, 2010.
More Object Concepts— Farrell, Chapter 4 Dr. Burns.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Classes - Intermediate
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
SUMMARY OF CHAPTER 2: JAVA FUNDAMENTS STARTING OUT WITH JAVA: OBJECTS Parts of a Java Program.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
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.
Functions + Overloading + Scope
3 Introduction to Classes and Objects.
Static data members Constructors and Destructors
Introduction to Classes and Objects
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Objects and Classes.
2.5 Another Java Application: Adding Integers
Object Oriented Systems Lecture 03 Method
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Methods.
CMSC 202 Static Methods.
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.
Starting Out with Java: From Control Structures through Objects
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Chapter 2 - Introduction to Java Applications
Variables and Their scope
Classes and Objects 5th Lecture
CHAPTER 6 GENERAL-PURPOSE METHODS
Chapter 3: Introduction to Objects and Input/Output
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Introduction to Java Programming
Method of Classes Chapter 7, page 155 Lecture /4/6.
Classes and Objects Static Methods
Classes, Objects and Methods
JOptionPane class.
F II 2. Simple Java Programs Objectives
Class rational part2.
Methods/Functions.
Chapter 2: Java Fundamentals cont’d
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Methods

Methods are groups of statements placed together under a single name. All Java applications have a class which includes a main method class MyClass { public static void main(String[] args) {... statements }

Methods All Java applications have a main method. Many of the statements in our main methods have invoked, or called, other library methods such as println, parseInt and showInputDialog. It is often convenient to write and call our own methods, to simplify the code in the main method (and elsewhere).

Car repair bill with methods 01 import javax.swing.*; 02 class CarRepair 03 { 04 public static void main(String[] args) 05 { 06 String partsStr = read("What is the parts cost"); 07 String hoursStr = read("How many hours"); 08 double parts = Double.parseDouble(partsStr); 09 double hours = Double.parseDouble(hoursStr); 10 // calculate bill before VAT 11 double bill = parts + hours * 20; 12 // add VAT 13 bill *= 1.175; // same as bill = bill * 1.175; 14 display("Your bill is £" + bill); 15 }

Car repair bill with methods 17 private static void display(String s) 18 { 19 JOptionPane.showMessageDialog(null, s); 20 } private static String read(String prompt) 23 { 24 return JOptionPane.showInputDialog(prompt); 25 } }

Car repair bill with methods In this version we have defined two private methods read and display. These make use of JOptionPane methods. The main method calls the read method at lines 06 and 07, and the display method at line 14. The method definitions at lines 17 – 20 and 22 – 25 can be thought of as recipes or methods for displaying an output string and reading an input string with a given prompt. When we write the main method we can forget about the fiddly JOptionPane methods and use the simpler display and read methods instead.

Parameters and arguments When we write methods we may specify one or more parameters in the method header between ( and ). The display method has a parameter String s and the read method has a parameter String prompt When we use a method we pass arguments across to these parameters. For instance in the main program we pass the argument "How many hours" for the call of read at line 07 across to the parameter String s at line 17.

Car repair bill with methods – design diagram The third box documents the methods used. – means private

Subroutines and functions Subroutine methods do something useful without returning a value. Examples of these are the main method of an application and the library methods println and showMessageDialog. These use the keyword void in their header as in private static void display(String s)... Function methods return a value. Examples of these are the library methods showInputDialog (which returns a String value), parseInt (which returns an int value) and parseDouble (which returns a double value). These use a type (primitive or class) in their header as in private static String read(String prompt)...

Subroutines and functions Function methods must include at least one return statement to return the required value as in return JOptionPane.showInputDialog(prompt); and the value returned must match the type specified in their header (here a String is returned). Subroutine methods don’t need return statements but may include statements of the form return; in which case the rest of the method is ignored and control passed back to the calling method.

Modifiers The keywords public, private and static are method modifiers. public methods may be called from outside the classes in which they are defined. private methods may only be called from other methods defined in the same class. Their job is just to simplify the code in other methods and make the code easier to understand. static methods belong to the class itself, and not to the objects created by the class. static methods may be public or private. Non- static (or dynamic) methods have access to the inner state of class objects. (This will become clearer in the next section).

Library methods The Java class libraries contain thousands of methods, both static and dynamic. static methods include –JOptionPane.showInputDialog(...) –JOptionPane.showMessageDialog(...) –Integer.parseInt(...) –Double.parseDouble(...)

Library methods The Java class libraries contain thousands of methods, both static and dynamic. Dynamic methods include –System.out.println(...); –Date now = new Date(); int thisYear = now.getYear() ;

Library methods When calling a static method we always use ClassName.methodName(arguments) unless the calling and called methods are in the same class.

Library methods When calling a dynamic method we always use object.methodName(arguments) unless the calling and called methods are in the same class.

Car repair revisited We could add an extra private method calculateBill(...) to carry out the actual calculation

Car repair revisited 01 import javax.swing.*; 02 class CarRepair2 03 { 04 public static void main(String[] args) 05 { 06 String partsStr = read("What is the parts cost"); 07 String hoursStr = read("How many hours"); 08 double parts = Double.parseDouble(partsStr); 09 double hours = Double.parseDouble(hoursStr); 10 double bill = calculateBill(parts, hours); 11 display("Your bill is £" + bill); 12 }

Car repair revisited 14 private static void display(String s) 15 { 16 JOptionPane.showMessageDialog(null, s); 17 } private static String read(String prompt) 20 { 21 return JOptionPane.showInputDialog(prompt); 22 } private static double calculateBill(double p, double h) 25 { 26 double b = p + h * 20; 27 return b * 1.175; 28 } }

Scope of variables So far we have used local variables. The scope of a local variable is the code where it may be referred to, and is simply the method in which it is defined. (This applies to the method’s parameters too). For instance the scope of the variable parts declared at line 08 in CarRepair2 is the main method lines 04 – 12. Any reference to parts outside this scope would be an error in this program (but see below).

Scope of variables Within a particular method we have complete freedom in naming the variables and parameters. calculateBill could have been defined like this: 24private static double calculateBill(double parts, double hours) 25 { 26 double bill = parts + hours * 20; 27 return bill * 1.175; 28 } with no difference to the compiled program. There are now two variables named parts - one in the main program declared at line 08 and one which is a parameter of the calculateBill method at line 24. The Java compiler decides which of these two is intended; the references at lines 8 and 10 are to the variable in the main program, the reference at line 26 is to the parameter of calculateBill.