Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
Advertisements

Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
 2006 Pearson Education, Inc. All rights reserved Functions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Road Map Introduction to object oriented programming. Classes
 2006 Pearson Education, Inc. All rights reserved Functions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Java: How to Program Methods Summary Yingcai Xiao.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
 2006 Pearson Education, Inc. All rights reserved Functions.
Introduction to Methods
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Python quick start guide
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Writing Classes (Chapter 4)
Dale Roberts Procedural Programming using Java Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
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.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Part II © Copyright by Pearson Education, Inc. All Rights Reserved.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
4-Methods Dr. John P. Abraham Professor UTPA. Common ways of packaging code Properties Methods Classes Namespaces (related classes are grouped into a.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Functions Review.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Object Oriented Programming with Java 03 - Introduction to Classes and Objects.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 15,16 Java’s Methods.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CSCI 3328 Object Oriented Programming in C# Chapter 6: Methods 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
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.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
(C) 2010 Pearson Education, Inc. All rights reserved.  Best way to develop and maintain a large program is to construct it from small, simple pieces,
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
Chapter 3: Using Methods, Classes, and Objects
Programming Fundamentals Lecture #7 Functions
6 Functions.
Chapter 6 Methods: A Deeper Look
Defining Your Own Classes
Chapter 6 Methods: A Deeper Look
MSIS 655 Advanced Business Applications Programming
Object Oriented Programming in java
Chapter 6 Methods.
CSCI 3328 Object Oriented Programming in C# Chapter 6: Methods
6 Methods: A Deeper Look.
Object Oriented Programming in java
Classes, Objects and Methods
Java Methods: A Deeper Look Academic 2019 Class: BIT23/BCS10 Chapter 06 Abdulaziz Yasin Nageye Faculty of Computing Java How to Program, 10/e 1 © Co py.
6 Functions.
Corresponds with Chapter 5
Presentation transcript:

Methods: A Deeper Look

Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc. constructors)

Template for Class Definition class { } Import Statements Class Comment Class Name Data Members Methods (incl. Constructor) Methods (incl. Constructor)

Data Member Declaration ; private String ownerName ; Modifiers Data Type Name Note: There’s only one modifier in this example.

Method Declaration ( ){ } public void setOwnerName ( String name ) { ownerName = name; } Statements Modifier Return Type Method Name Parameter

Constructor A constructor is a special method that is executed when a new instance of the class is created. public ( ){ } public Bicycle ( ) { ownerName = “ Unassigned ” ; } Statements Modifier Class Name Parameter

Program Modules in Java Methods Called functions or procedures in other languages Modularize programs by separating its tasks into self-contained units Enable a divide-and-conquer approach Are reusable in later programs Prevent repeating code

Program Modules in Java Java Application Programming Interface (API) Also known as the Java Class Library Contains predefined methods and classes Related classes are organized into packages Includes methods for mathematics, string/character manipulations, input/output, databases, networking, file processing, error checking and more

Good Programming Practice 6.1 Familiarize yourself with the rich collection of classes and methods provided by the Java API (java.sun.com/j2se/5.0/docs/api /index.html).

Software Engineering Hint To promote software reusability, every method should be limited to performing a single, well-defined task, and the name of the method should express that task effectively. Such methods make programs easier to write, debug, maintain and modify.

What if we see this method: public static void main(String args) { }

static Methods, static Fields and Class Math static method (or class method) Applies to the class as a whole instead of a specific object of the class Call a static method by using the method call: ClassName. methodName ( arguments ) All methods of the Math class are static example: Math.sqrt( )

static Methods, static Fields and Class Math (Cont.) Constants Keyword final Cannot be changed after initialization static fields (or class variables) Are fields where one copy of the variable is shared among all objects of the class Math.PI and Math.E are final static fields of the Math class

Math class methods.

static Methods, static Fields and Class Math (Cont.) Method main main is declared static so it can be invoked without creating an object of the class containing main Any class can contain a main method The JVM invokes the main method belonging to the class specified by the first command-line argument to the java command

Practice (Car – Driver scenario) Step 1: Create a Lab8 folder, under it create Car class. Cut and Paste Car.java from D2L. Step 2: Create another class CarAndDriver. Cut and Paste the class: CarAndDriver.java from D2L. Step 3: Implement two methods with stubs in Car.java Step 4: According to the comments in Car class, identify and implement two methods that are not even declared with stubs. Step 5: Compile Car class, if there is any compiling errors, please fix them

Practice (Car – Driver scenario) Step 6: Open CarAndDriver class, please insert your code according to the comments. Step 7: Run your program.

Discussion When to declare a method as static? Step 1: Under Lab8 folder, create a class called MrHappyObject. Cut and Paste MrHappyObject.java from D2L Step 2: Under Lab 8 folder, create a class called MrHappyObjectMain. In this class you need to: - create two MrHappyObject namely obj1 and obj2. - print out the mood for these two objects after you created them.

Discussion Step 3: obj1 receives a hug while obj2 reveives a punch. Print out the mood for obj1 and obj2 after all these actions. Step 4: What did you see in the screen? Step 5: In MrHappyObject.java class, insert these: public MrHappyObject() { instantiations++; } public static int instances() { return instantiations; }

Discussion Step 6: In MrHappyObjectMain class, print out the number of instances right after you create both obj1 and obj2 print out the number of instances right both punching and hugging taken happened for obj1 and obj2. Step 7: Describe what you see on the screen and why?

Discussion Good candidates for static methods: Methods that don’t depend on an instance’s state Static methods are proven useful for creating utility classes (example: Math class is a utility class that contains all utilities for computing Mathematical functions)

Declaring Methods with Multiple Parameters Multiple parameters can be declared by specifying a comma-separated list. Arguments passed in a method call must be consistent with the number, types and order of the parameters Sometimes called formal parameters

A Quick Review 1. An argument is a value we pass to a method, and a parameter is a placeholder for arguments a. True b. False

A Quick Review 2. An argument is a value we pass to a method, and a parameter is a placeholder for arguments a. True b. False

Arguments and Parameters The number of arguments and the parameters must be the same Arguments and parameters are paired left to right The matched pair must be assignment- compatible (e.g. you cannot pass a double argument to a int parameter)

Notes on Declaring and Using Methods Three ways to call a method: Use a method name by itself to call another method of the same class Use a variable containing a reference to an object, followed by a dot (. ) and the method name to call a method of the referenced object Use the class name and a dot (. ) to call a static method of a class static methods cannot call non- static methods of the same class directly

Notes on Declaring and Using Methods (Cont.) Three ways to return control to the calling statement: If method does not return a result: Program flow reaches the method-ending right brace or Program executes the statement return; If method does return a result: Program executes the statement return expression ;  expression is first evaluated and then its value is returned to the caller

Method Call Stack and Activation Records Stacks Last-in, first-out (LIFO) data structures Items are pushed (inserted) onto the top Items are popped (removed) from the top Program execution stack Also known as the method call stack Return addresses of calling methods are pushed onto this stack when they call other methods and popped off when control returns to them

Method Call Stack and Activation Records (Cont.) A method’s local variables are stored in a portion of this stack known as the method’s activation record or stack frame When the last variable referencing a certain object is popped off this stack, that object is no longer accessible by the program  Will eventually be deleted from memory during “garbage collection” Stack overflow occurs when the stack cannot allocate enough space for a method’s activation record

Argument Promotion and Casting Argument promotion Java will promote a method call argument to match its corresponding method parameter according to the promotion rules Values in an expression are promoted to the “highest” type in the expression (a temporary copy of the value is made) Converting values to lower types results in a compilation error, unless the programmer explicitly forces the conversion to occur

Promotions allowed for primitive types.

Java API Packages Java API documentation java.sun.com/j2se/5.0/docs/api/index.html Overview of packages in JDK 5.0 java.sun.com/j2se/5.0/docs/api/overview- summary.html java.sun.com/j2se/5.0/docs/api/overview- summary.html

Java API packages (a subset). (Part 1 of 2)

Java API packages (a subset). (Part 2 of 2)

Scope of Declarations Basic scope rules Scope of a parameter declaration is the body of the method in which appears Scope of a local-variable declaration is from the point of declaration to the end of that block Scope of a local-variable declaration in the initialization section of a for header is the rest of the for header and the body of the for statement Scope of a method or field of a class is the entire body of the class

Scope of Declarations (Cont.) Shadowing A field is shadowed (or hidden) if a local variable or parameter has the same name as the field This lasts until the local variable or parameter goes out of scope

Method Overloading Method overloading Multiple methods with the same name, but different types, number or order of parameters in their parameter lists Compiler decides which method is being called by matching the method call’s argument list to one of the overloaded methods’ parameter lists A method’s name and number, type and order of its parameters form its signature

Method Overloading Differences in return type are irrelevant in method overloading Overloaded methods can have different return types Methods with different return types but the same signature cause a compilation error