Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "01/24/2005 Introduction to Programming with Java, for Beginners A Closer Look at Constructors and Methods."— Presentation transcript:

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

2 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

3 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

4 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”);

5 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.

6 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.

7 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)

8 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);

9 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)

10 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

11 01/24/2005CSE 11010 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

12 01/24/2005CSE 11011 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)

13 01/24/2005CSE 11012 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

14 01/24/2005CSE 11013 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

15 01/24/2005CSE 11014 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

16 01/24/2005CSE 11015 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

17 01/24/2005CSE 11016 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”

18 01/24/2005CSE 11017 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


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

Similar presentations


Ads by Google