01/24/2005 Introduction to Programming with Java, for Beginners A Closer Look at Constructors and Methods.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Introduction to Programming G51PRG University of Nottingham Revision 3 Essam Eliwa.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Lecture 2: Object Oriented Programming I
Introduction to Programming with Java, for Beginners Intro OOP with Java Java Program Structure.
Access to Names Namespaces, Scopes, Access privileges.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Introduction to Programming with Java, for Beginners Control Structures.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
11 Methods1June Methods CE : Fundamental Programming Techniques.
Introduction to Programming with Java, for Beginners Conditionals (if statements)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Parameters, Arguments, Local Variables, and Scope CSC 1401: Introduction to Programming with Java Week 8 – Lecture 1 Wanda M. Kunkle.
Introduction to Programming with Java, for Beginners Scope.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
Lecture From Chapter 6 & /8/10 1 Method of Classes.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
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.
Chapter 10 METHODS AND CONSTRUCTORS 1. Accessing Objects  Referencing the object’s data: objectReference.data myCircle.radius  calling the object’s.
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.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Methods. 2 A sequence of statements can be packaged together as a unit and re-used. A method is a named unit of re-usable code. modifier returnType methodName(
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.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
ECE122 Feb. 22, Any question on Vehicle sample code?
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
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.
Writing Static Methods Up until now, we have been USING (calling) static methods that other people have written. Now, we will start CREATING our own static.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
02/14/2005 Introduction to Programming with Java, for Beginners Midterm 1 Review.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
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.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
CIS 234: Java Methods Dr. Ralph D. Westfall April, 2010.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
CSI 3125, Preliminaries, page 1 Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name,
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Java Part I By Wen Fei, HAO. Program Structure public class ClassName { public static void main(String[] args) { program statements } user defined methods.
Class Fundamentals BCIS 3680 Enterprise Programming.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
Chapter 7 User-Defined Methods.
3 Introduction to Classes and Objects.
Yanal Alahmad Java Workshop Yanal Alahmad
Methods Chapter 6.
Yanal Alahmad Java Workshop Yanal Alahmad
Object Oriented Systems Lecture 03 Method
SELECTION STATEMENTS (1)
Method Mark and Lyubo.
Introduction to Programming with Java, for Beginners
Control Structures (Structured Programming) for controlling the procedural aspects of programming CS1110 – Kaminski.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
An Introduction to Java – Part I, language basics
T. Jumana Abu Shmais – AOU - Riyadh
Class Everything if Java is in a class. The class has a constructor that creates the object. public class ClassName private Field data (instance variables)
Method of Classes Chapter 7, page 155 Lecture /4/6.
Classes, Objects and Methods
Control Structures (Structured Programming) for controlling the procedural aspects of programming CS1110 – Kaminski.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Methods/Functions.
Corresponds with Chapter 5
Presentation transcript:

01/24/2005 Introduction to Programming with Java, for Beginners A Closer Look at Constructors and Methods

01/24/2005CSE 1101 Constructor & Method Review ConstructorMethod Purpose Create an objectExecute object behavior Name Same as the class it’s in; upper case with “camel caps” A verb; lower case with “camel caps” Code public Taxi(){ … } public void turnLeft(){ … } Output No return typeReturn type required Input 0 or more parameters Usage > Taxi cab; > cab = new Taxi();> cab.turnLeft(); # calls At most once per objectUnlimited times per object

01/24/2005CSE 1102 import java.util.*; public class Taxi{ private int miles; public Taxi(){ miles = 0; } public int getMiles(){ return miles; } import and package statements Class header. { starts class body Instance variables/fields Constructors Methods } ends class body Anatomy of a Class

01/24/2005CSE 1103 A Class with Two Constructors public class Taxi{ private int miles; private String driver;.. public Taxi(){ miles = 0; driver = “Unknown”; } public Taxi(int m,String d){ miles = m; driver = d; } Object Creation > Taxi cab1; > cab1 = new Taxi(); > Taxi cab2; > cab2 = newTaxi(5,”Jo”);

01/24/2005CSE 1104 What is a Constructor? A named piece of code that runs when an object is created. Purpose: initialize an object’s state. Declaration: public ClassName(0+ parameters){.. } Name: same as its class Output: no return type (but delivers a new object) Input: 0 or more parameters. How it’s “called” (run/invoked/executed): “new” operator. new ClassName(0+ arguments) The “new” operator finds the named class and runs the only constructor whose parameters match the input args (by number, type, and order). Default Constructor: Created by Java if a class has no constructors public ClassName(){} Better to explicity create a constructor and intialize state.

01/24/2005CSE 1105 What is a Method? A named piece of code in a class (that’s not a constructor). Purpose: Make an object “do something”*. A method may: Change its object’s state Report its object’s state Operate on numbers, text, files, graphics, web pages, hardware, … Create other objects Call another method in the same class: method(args); Call another object’s method: obj.method(args) Call itself (recursion): sameMethod(args); And much more, as we’ll see! * Advanced: A “static” method pertains to a class vs. an individual object.

01/24/2005CSE 1106 Method Declaration public return_type methodName(0+ parameters){..} public int getMiles() {..} public void increaseSpeed(int accel, int limit){..} Name: Verb starting with a lowercase letter, with “camel caps” Ouput: Return type required. Input: 0 or more parameters Body: Enclosed by curly braces Contains an arbitrary # of statements (assignment, “if”, return, etc.). May contain “local variable” declarations How it’s called: “dot” operator: objectName.methodName(arguments) cab1.increaseSpeed(5, 65)

01/24/2005CSE 1107 “Getter” and “Setter” Methods public class Taxi{ private int miles; … // gets/returns # miles public int getMiles(){ return miles; } // sets/changes # miles public void setMiles(int m){ miles = m; } Getter/setter calls > int m; > m = cab.getMiles(); > cab.setMiles(500);

01/24/2005CSE 1108 A Method’s Input A method may receive 0 or more inputs. A method specifies its expected inputs via a list of “formal parameters” (type1 name1, type2 name2, …) In a method call, the number, order, and type of arguments must match the corresponding parameters. Method Declaration (with parameters) Method Call (with arguments) public void foo1(){..}obj.foo1() public int foo2(boolean b){..}obj.foo2(true) public int foo3(int x,int y,Taxi t){..}obj.foo3(3,4,cab)

01/24/2005CSE 1109 A Method’s Output A method may output nothing or one thing. Either way, it must have a “return type”. If it outputs nothing: void return type public void setMiles(int miles){..} No return statement If it outputs one thing: non-void return type (e.g int, boolean, Taxi) public int getMiles(){..} Must have a return statement, where the type of the value returned must match the return type return miles; // the type of miles is int

01/24/2005CSE Constructor & Method Review ConstructorMethod Purpose Create an objectExecute object behavior Name Same as the class it’s in; upper case with camel caps A verb; lower case with camel caps Code public Taxi(){ … } public void turnLeft(){ … } Output No return typeReturn type required Input 0 or more parameters Usage > Taxi cab; > cab = new Taxi();> cab.turnLeft(); # calls At most once per objectUnlimited times per object

01/24/2005CSE CodeExplanation // Converts 0,1,2,3 to “north”, // “east”, “south”, “west” public String getDirection(){ String result; if (direction == 0) result = "north"; else if (direction == 1) result = "east"; else if (direction == 2) result = "south"; else if (direction == 3) result = "west"; else result = "unknown"; return result; } Methods may have “local variables” (e.g. result), which are known from the point of declaration until the end curly brace of the block in which they are declared. In contrast, instance variables are declared outside of any method and are known to all methods in the class in which they’re declared. Local Variables (in a Method)

01/24/2005CSE int x = 5; int y = 10; if (x < y){ x = y; } // Now both x and y are 10 if (condition){ statement(s) } If the condition is true, then the statement(s) will be executed. Otherwise, they won’t. int num1 = 20; int num2 = 40; int temp = 0; if (num1 < num2){ temp = num1; num1 = num2; num2 = temp; } //num1 is 40, num2 is 20 Here’s how to “swap” the values of two variables by using a temporary variable. “if” statement

01/24/2005CSE Code in a Hypothetical GameSyntax & Explanation boolean done; done = promptUser(“Quit?”); if (done == true){ saveGameState(); quit(); } else { resetGameState(); playGame(); } if (condition){ statement(s) } else { statements(s) } If the condition is true, then the statement(s) in the “if block”* are executed. Otherwise, if there is an “else block”*, the statements in it are executed. * code within curly braces “if-else” statement

01/24/2005CSE Code in a Hypothetical GameSyntax char choice = getChoice(); if (choice == ‘f’){ fire(); } else if (choice == ‘l’){ turnToLeft(); } else if (choice == ‘r’){ turnToRight(); } else { gatherIntelligence(); } if (condition1){ statement(s) } else if (cond2){ statements(s) }.. else{ statements(s) } Why is this more efficient than using several separate “if” statements? Cascading “if-else” statement

01/24/2005CSE An if within an ifTruth Table if (condition1){ if (condition2){ statement(s) A } else{ statement(s) B } else { statements(s) C } What values must the conditions have in order for block A to run? B? C? Nested “if” statement ABC condition1 T condition2

01/24/2005CSE CodeNotes if (x > y) if (y < z) System.out.println(“A”); else System.out.println(“B”); The person that coded this expects “B” to print if (x > y) is false. But it doesn’t. Why not? What is a fix? Hint 1: An else is paired with the last else- less if. Hint 2: Fix with curly braces {}. The infamous “dangling else”

01/24/2005CSE import java.util.*; public class Taxi{ private int miles; public Taxi(){ miles = 0; } public int getMiles(){ return miles; } import and package statements Class header. { starts class body Instance variables/fields Constructor Declarations Method Declarations } ends class body Anatomy of a Class