CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.

Slides:



Advertisements
Similar presentations
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Road Map Introduction to object oriented programming. Classes
Chapter 41 Defining Classes and Methods Chapter 4.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Chapter 15: Operator Overloading
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
ECE122 Feb. 22, Any question on Vehicle sample code?
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Procedural programming in Java Methods, parameters and return values.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
CSE 501N Fall ‘09 04: Introduction to Objects 08 September 2009 Nick Leidenfrost.
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
CSE 1301 Lecture 6 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
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.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
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.
1 Review for Midterm 2 Aaron Bloomfield CS 101-E.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
Information and Computer Sciences University of Hawaii, Manoa
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
JavaScript: Functions.
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.
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.
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
CHAPTER 6 GENERAL-PURPOSE METHODS
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Corresponds with Chapter 5
Presentation transcript:

CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost

2 Lecture Outline Boolean Expressions Methods  Naming  Parameter Lists  Return Types  Invoking / Calling Control Flow Lab 1 Overview

3 Boolean Expressions An expression is a combination of one or more operators and operands Last lecture we learned about arithmetic expressions – expressions dealing with numeric types as operands and the operators +, -, *, / and % Boolean expressions compute logical results and make use of the boolean operators: Name: Java Operator AND&& OR| | NOT! XOR^

4 Boolean Expressions AND (&&) – Binary operator that evaluates to true if both operands are true OR ( | | ) – Binary operator that evaluates to true if either of the operands are true XOR ( ^ ) – Binary operator that evaluates to true if one and only one of the operands are true NOT ( ! ) – Unary operator that negates the value of an operator boolean one, two; boolean allOrNone = one && two; boolean eitherOne = one || two; boolean onlyOne = one ^ two; boolean negated = !one;

5 Boolean Expressions Truth Tables A truth table is a tool we can use to verify the results of a boolean expression for all input values [ Truth Tables on Board ] p q p && q T T T T F F F T F F F F

6 Boolean Operators #1NOT (!) #2AND (&&) #3XOR (^) #4OR (||) Precedence Like arithmetic expressions, boolean expressions can be complex Like arithmetic expressions, parenthesis can be used to override precedence (done || found) && !interupted done || found && !interupted

7 Advanced Boolean Operations NAND  !(a && b)  (!a || !b) NOR  !(a || b)  (!a && !b)

8 Broadening Our Programming Context Up till now, we’ve learned:  How to declare primitive variables ints, doubles, booleans, etc.  How to combine variables, constants, and operators to form complex expressions Arithmetic Expressions Boolean Expressions  We can use these to change the value of variables with assignment operators

9 Review Basic Structure of a Java Program public class Calculator { } /* Calculator.java Nick Leidenfrost Example program */ public static void main (String[] args) { } // this method starts my program // statements to be executed here...

10 Methods Introduction Many of us are familiar with the concept of a function from mathematics: We put in some input We get some defined output In general, a method in Java is pretty much the same thing: f(x) = 2x + 5 The value resulting from this calculation is our output public int calc (int x) { return 2*x + 5; } Here is our Input Here is the expression that uses our input to calculate our output

11 Methods Anatomy Method declarations are composed of 4 main parts:  Method Name  Parameter List  Method Body  Return Type You may see methods defined with words like “public” and “private” in front of them  These are called access modifiers  You can remain blissfully ignorant of them for another week public int calc (int x) { return 2*x + 5; } The method name can be any identifier we want The parameter list contains local variable declarations for the input passed into the method. (The name and type of each parameter) The method body is enclosed in curly braces ({ and }) and contains an arbitrary number of statements The return type defines the type of the output that the method produces. This can be any primitive or object type. Collectively, the name, parameter list, return type and access modifier make up the method signature

12 Methods Detail: Parameters (Input) When declaring a method, we can specify any number of parameters that we decide we need: The parameters can be of any type, and can be named with any legal identifier public int calcY (int x) { return 2*x + 5; } public int calcY (int slope, int x, int yOffset) { return slope*x + yOffset; }

13 Methods Detail: Naming & Identifiers Can two methods have the same name?  Yes, actually. This is known as overloading the method.  The methods can have the same name, but cannot have the same method signature Why is this useful?  Accepting different types of input to perform a calculation  Specifying default values public int calcY (int x) { return calcY(2, x, 5); }

14 Methods Detail: Return Type The return type of a method specifies what the type of the output will be, e.g.  int, double, boolean, etc. If a method has no output, it has a return type of void void doSomething () { }

15 Methods Invoking / Calling Methods We can execute a method by invoking or calling the method.  To invoke a method, we use the method’s name, and any required input arguments surrounded by parenthesis: Notice that the formal and actual parameters have the same type Also, notice how I am using the method as the Right- Hand Side of an assignment operation  This stores the output of the method into the local variable y public int calcY (int x) { return 2*x + 5; } int myXVal = 2; int y = calcY(myXVal); The parameters in the method declaration are referred to as the formal parameters The arguments passed in when the method is invoked are referred to as the actual parameters

16 Methods Invoking / Calling Methods If a method requires no parameters, we invoke it with just the method name and empty parenthesis int y = generateRandom();

17 Methods The return Statement: Output The return statement specifies what the output of the method will be The return statement must evaluate to a type that is assignable (convertible by assignment) to the return type The Right-Hand Value of the method Must be the last statement to execute in the method public int calcY (int slope, int x, int yOffset) { int y = slope*x + yOffset; return y; }

18 Methods The return Statement: Output (or lack thereof) What if a method has a void return type – can it still have a return statement?  Yes, but the return statement cannot include any variable or expression Can a method with a void return type be used as the Right-Hand side of an assignment?  No. public void calcY (int slope, int x, int yOffset) { int y = slope*x + yOffset; System.out.println(y); return; }

19 Method Control Flow Invoking Methods & Control Flow Control flow (or flow of control) is a term that refers to the order of executions of statements within a program  We will learn about many ways of manipulating control flow Conditional Statements Loops When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined

20 Methods Invoking Methods & Control Flow When a method is invoked:  The actual parameters are copied into the formal parameters  Control flow (execution) is transferred to inside the method’s body  The statements inside the method body are executed  The method ends and returns control flow to the caller The method body ends (the method is a void method) A return statement is reached  The value returned is copied and passed to the caller All of the method’s local variables are destroyed

21 Sample Program public class CubeANumber { public static void main (String[] args) { int cube; cube = cube(5); System.out.println(cube); } public static int cube (int toCube) { int squared = square(toCube); return toCube*squared; } public static int square (int toSquare) { return toSquare*toSquare; }

22 int cube (int num) { int square (int num) { square(5); cube(5); void main () { Method Control Flow } } }

23 Methods in OOP Methods as Class Members In Java, all methods are defined within a class definition Methods define the behavior of the objects of that class In OOP, methods can be categorized generally as:  Accessors Retrieve an object’s state (return the value of fields)  Mutators Manipulate an object’s internal state  Subroutines Used by other methods in the program – “Helper methods” // You will have 1 of these in Lab 1 // You will have 2 of these in Lab 1 // The rest of the Lab 1 methods

24 Methods Benefits: Abstraction Methods can help support abstraction  The process of hiding detail Methods specify what inputs it needs (parameters) Methods specify what outputs it produces (return values) How it translates the inputs to outputs is hidden from the programmer Square Root Method aSqrt(a)

25 Methods Benefits: Code Reuse Methods promote code reuse and maintainability A problem can be solved generally by the method for any input If we define functionality in one place (inside the method) and need to make a change, we only need to make that change in one place

26 Lab 1 Overview public class Calculator { public int plus (int a, int b) { return a+b; } // Method Skeleton public double plus (double a, double b) { return 0.0; }

27 Lab 1 Overview Real Programming -> Errors A program can have three types of errors  Compile-time errors Syntax and logical errors that can be identified by the compiler. Prior to execution  Run-time Errors A problem occurring during program execution, which causes a program to terminate abnormally  Semantic Errors The program runs, but produces incorrect / undesired results

28 Lab 1 Overview Eclipse IDE We will be using the IDE Eclipse for the rest of our labs this semester  You can use another IDE, if you prefer But I probably won’t know how to use it well…

29 Lab 1 Overview Memory Operations Some methods you are asked to implement, the “memory” operations will require interaction with an instance variable  Instance variables are variables that are defined inside a class body rather than inside a method body  We will learn about these on Tuesday When we take our next step towards awesomeness: Classes and Objects

30 Conclusion Questions? Lab 1 Assigned  On the website  Due Next Thursday  I will be in Lab now.