26-Jun-15 Methods. About methods A method is a named group of declarations and statements If a method is in the same class, you execute those declarations.

Slides:



Advertisements
Similar presentations
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1 Java Programming Basics SE-1011 Dr. Mark L. Hornick.
Internal Documentation Conventions. Kinds of comments javadoc (“doc”) comments describe the user interface: –What the classes, interfaces, fields and.
CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
Road Map Introduction to object oriented programming. Classes
Access to Names Namespaces, Scopes, Access privileges.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
16-Jun-15 javadoc. 2 Javadoc placement javadoc comments begin with /** and end with */ In a javadoc comment, a * at the beginning of the line is not part.
19-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
20-Jun-15 Methods. Complexity The programmer's biggest adversary is complexity The programmer's biggest adversary is complexity Primitive types and the.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements You execute those declarations and statements by calling the.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
30-Jun-15 Static Methods. About methods A method is a named group of declarations and statements You execute those declarations and statements by calling.
Chapter 7: User-Defined Methods
Introduction to Methods
CS/ENGRD 2110 SPRING 2013 Lecture 2: Introduction to Java 1.
COMP More About Classes Yi Hong May 22, 2015.
1 Web Based Programming Section 6 James King 12 August 2003.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
NSIT,Jetalpur CORE JAVA CONCEPTS SURABHI MISHRA (LCE)NSIT.
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.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
The Java Programming Language
Utilities (Part 2) Implementing static features 1.
CIT 590 Intro to Programming First lecture on Java.
Objective You will be able to define and identify the basic components of a java program by taking notes, seeing examples, and completing a lab. Construction.
Introduction to programming in the Java programming language.
INTERFACES More OO Concepts. Interface Topics Using an interface Interface details –syntax –restrictions Create your own interface Remember polymorphism.
Vladimir Misic: Java1 Basic Java Syntax The java language will be described by working through its features: –Variable types and expressions.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CSC 142 D 1 CSC 142 Instance methods [Reading: chapter 4]
Javadoc. Purpose of javadoc javadoc is a program that reads your Java program and produces great-looking documentation in HTML format Without any help,
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.
1  lecture slides online
24-Dec-15 Class Structure. 2 Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
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.
CSC 212 – Data Structures Lecture 5: Variables. Problem of the Day Why do underground subway stations always have more escalators going up than down?
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
OOP Basics Classes & Methods (c) IDMS/SQL News
COP 2220 Computer Science I Topics –Breaking Problems Down –Functions –User-defined Functions –Calling Functions –Variable Scope Lecture 4.
Today Javadoc. Packages and static import. Viewing API source code. Upcoming Topics: –protected access modifier –Using the debugger in Eclipse –JUnit testing.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Variable Scope & Lifetime
Information and Computer Sciences University of Hawaii, Manoa
Class Structure 15-Jun-18.
Some Eclipse shortcuts
Static Methods 14-Nov-18.
Class Structure 16-Nov-18.
Classes, Objects, and Methods
Class Structure 28-Nov-18.
Class Structure 7-Dec-18.
Class Structure 2-Jan-19.
Namespaces, Scopes, Access privileges
Anatomy of a Java Program
Class Structure 25-Feb-19.
Classes, Objects and Methods
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Classes and Methods 15-Aug-19.
Presentation transcript:

26-Jun-15 Methods

About methods A method is a named group of declarations and statements If a method is in the same class, you execute those declarations and statements by calling the method If the method belongs to some other object, you execute it by sending a message to that object When you call the method, you can give it parameters (information, such as numbers, going into the method) A method typically has a return value (a single piece of information coming out of the method) Declarations and statements parameter return value

Example method Inside a CokeMachine class, you might have this method: public void insertCoin(int coin) { // “coin” is a parameter if (coin == 5 || coin == 10 || coin == 25) { amountEntered = amountEntered + coin; } } Inside the CokeMachine class, you might have code like this: int dime = 10; insertCoin(dime); // this is a call to the insertCoin method In some other class, you might have code like this: CokeMachine cheater = new CokeMachine(); CokeMachine honestAbe = new CokeMachine(); int dime = 10; honestAbe.insertCoin(dime); // this is a message to honestAbe

Why methods? Methods help you break up a complex problem into simpler subproblems, which you can solve separately Methods can use other methods, but should not depend on the “inner workings” of those other methods--just what they do, not how they do it Methods allow you to give names to parts of your computation, thus making your program more readable Readability is essential in good programming Proper choice of method names is important Verbs are usually best, since methods “do something” If you have anything the least bit complicated to compute, you should write (and debug) it in only one place This is an application of the DRY principle (“Don’t Repeat Yourself”) Methods are very good for putting code in only one place

Defining a method A method has the syntax: access return-type method-name ( parameters ) { method-variables code } The access ( public, protected, or private ) is optional Example: private boolean isAdult(int age) { int magicAge = 21; return age >= magicAge; } Example: double average(int a, int b) { return (a + b) / 2.0; }

Returning a result from a method If a method is to return a result, it must specify the type of the result: boolean isAdult ( … You must use a return statement to exit the method with a result of the correct type: return age >= magicAge ;

Returning no result from a method The keyword void is used to indicate that a method doesn’t return a value The return statement must not specify a value Example: void printAge(String name, int age) { System.out.println(name + " is " + age + " years old."); return; }  There are two ways to return from a void method:  Execute a return statement  Reach the closing brace of the method

Instance variables A variable declared within a class (but not within a method) is an instance variable Every object (“instance”) of that class has its own variable with that name Example: Every CokeMachine has its own amountEntered Instance variables are “visible”--available for use--everywhere within the class in which they are defined Instance variables should almost always be marked private, so that other classes cannot “see” them Example: You don’t want a Customer object to be able to change the amountEntered in a CokeMachine without inserting coins Every instance variable should say something meaningful about its object

Scope of variables Parameters to a method are visible throughout the method Parameters are discarded when the method returns Variables declared within a block (between { and } ) are visible from where they are declared up to the end of the block These variables are discarded when the block is exited Example: public double average(double x, double y, double z) { // x, y, and z are visible throughout this method double count = 3.0; // count is visible from here forward double avg = (x + y + z) / count; // avg is visible from here forward return avg; // the value of avg is returned, but the variable itself, // and the variable count, are discarded } Note that count and avg could be instance variables, but since they don’t say anything about the object they are in, this would be very poor style

Methods and static methods Java has two kinds of methods: static methods and non-static methods (also know as instance methods) However, before we can talk about what it means to be static, we have to learn a lot more about classes and objects Most methods you write should not, and will not be static Every Java program has a public static void main(String[ ] args) method This starts us in a “static context” To “escape from static”, I recommend starting every program in a certain way, as shown on the next slide

Escaping from static class MyClass { public static void main(String[] args) { new MyClass().run(); } void run() { // Your real code begins here } } You can replace the names MyClass and run with names of your choice, but notice that each name occurs in two places, and they have to match up

Documenting a method Javadoc comments start with /** and end with */, and are put immediately before the method The text is written as if the method description began with the words “This method...” The comment ends with the following name description (one for each parameter) The description tells what information the named parameter provides You don’t need to mention the parameter type—Javadoc knows that If any instance variables are used, their use should be described References to the object should be with “this”– this Tree, this JPanel, description A description of the value that is returned (omit if void exception cause (one for each Exception) Tells what condition will cause this Exception to be thrown HTML markup may be used within the Javadoc comment To generate the actual documentation from the comments (in Eclipse), do: Project  Generate Javadoc...

Example Javadoc documentation public class Pair { private static final long serialVersionUID = 1L; private Student student1; private Student student2;... /** * Returns one of the two students in this pair. The order of students * is irrelevant and should not be depended upon. * which 1 or 2. One of the students in this pair. */ public Student getStudent(int which) { if (which == 1) return student1; else if (which == 2) return student2; else error("There is no student " + which); return null; }... }

The End Though this be madness, yet there is method in it. --Shakespeare, Hamlet