Java Methods TM Maria Litvin Gary Litvin An

  • Slides: 43
Download presentation
Java Methods TM Maria Litvin Gary Litvin An Introduction to Object-Oriented Programming Chapter chapter

Java Methods TM Maria Litvin Gary Litvin An Introduction to Object-Oriented Programming Chapter chapter 8 = new Chapter(8); Methods, Constructors, and Fields Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights 1 reserved.

Objectives: l l Learn the syntax and style for defining and calling methods and

Objectives: l l Learn the syntax and style for defining and calling methods and constructors Learn how arguments are passed to methods and constructors and how to return values from methods Learn about static (class) and non-static (instance) fields and methods Review public and private fields and methods 2

Methods public [or private] return. Type method. Name (type 1 name 1, . .

Methods public [or private] return. Type method. Name (type 1 name 1, . . . , type. N name. N) { . . . } l Body Header To define a method: – decide between public and private (usually public) – give it a name – specify the types of arguments (formal parameters) and give them names – specify the method’s return type or chose void – write the method’s code 3

Methods (cont’d) l l l A method is always defined inside a class. A

Methods (cont’d) l l l A method is always defined inside a class. A method returns a value of the specified type unless it is declared void; the return type can be any primitive data type or a class type. A method’s arguments can be of any primitive data types or class types. Empty parentheses indicate that a method takes no arguments. public [or private] return. Type method. Name ( ) {. . . } 4

Methods: Java Style l Method names start with lowercase letters. l Method names usually

Methods: Java Style l Method names start with lowercase letters. l Method names usually sound like verbs. l The name of a method that returns the value of a field often starts with get: get. Width, get. X The name of a method that sets the value of a field often starts with set: set. Location, set. Text 5

Overloaded Methods l l Methods of the same class that have the same name

Overloaded Methods l l Methods of the same class that have the same name but different numbers or types of arguments are called overloaded methods. Use overloaded methods when they perform similar tasks: public void move (int x, int y) {. . . } public void move (double x, double y) {. . . } public void move (Point p) {. . . } public Fraction add (int n) {. . . } public Fraction add (Fraction other) {. . . } 6

Overloaded Methods (cont’d) l l The compiler treats overloaded methods as completely different methods.

Overloaded Methods (cont’d) l l The compiler treats overloaded methods as completely different methods. The compiler knows which one to call based on the number and the types of the arguments: public class Circle circle = new Circle(5); {. . . public void move (int x, int y) {. . . } public void move (Point p) {. . . }. . . circle. move (50, 100); . . . Point center = new Point(50, 100); circle. move (center); . . . } 7

Constructors l l l A constructor is like a method for creating objects of

Constructors l l l A constructor is like a method for creating objects of the class. A constructor often initializes an object’s fields. Constructors do not have a return type (not even void) and they do not return a value. All constructors in a class have the same name — the name of the class. Constructors may take arguments. 8

Constructors (cont’d) l l l If a class has more than one constructor, they

Constructors (cont’d) l l l If a class has more than one constructor, they are “overloaded” and must have different numbers and/or types of arguments. Programmers often provide a “no-args” constructor that takes no arguments. If a programmer does not define any constructors, Java provides one default no -args constructor, which allocates memory and sets fields to the default values. 9

Constructors (cont’d) public class Fraction { private int num, denom; public Fraction ( )

Constructors (cont’d) public class Fraction { private int num, denom; public Fraction ( ) { num = 0; denom = 1; } “Noargs” construc public Fraction (inttor n) public Fraction (int p, int q) { num = p; denom = q; reduce (); } { num = n; denom = 1; } Continued } public Fraction (Fraction other) { num = other. num; denom = other. denom; }. . . Copy construc tor 10

Constructors (cont’d) l Constructors of a class can call each other using the keyword

Constructors (cont’d) l Constructors of a class can call each other using the keyword this — a good way to avoid duplicating code: public class Fraction {. . . public Fraction (int n) { this (n, 1); }. . . public Fraction (int p, int q) { num = p; denom = q; reduce (); }. . . 11

Operator new l Constructors are invoked using new Fraction f 1 = new Fraction

Operator new l Constructors are invoked using new Fraction f 1 = new Fraction ( ); 0/1 Fraction f 2 = new Fraction (5); Fraction f 3 = new Fraction (4, 6); Fraction f 4 = new Fraction (f 3); 5/1 2/3 12

Operator new (cont’d) l You must create an object before you can use it;

Operator new (cont’d) l You must create an object before you can use it; the new operator is a way to do it Fraction f; f is set to null f = new Fraction (2, 3); Now f refers to a valid object f = new Fraction (3, 4); Now f refers to another object (the old object is “garbage-collected”) 13

Static Fields l l A static field (a. k. a. class field or class

Static Fields l l A static field (a. k. a. class field or class variable) is shared by all objects of the class. A static field can hold a constant shared by all objects of the class: Reserved public class Rolling. Die { private static final double slow. Down = 0. 97; private static final double speed. Factor = 0. 04; . . . l words: static final A non-static field (a. k. a. instance field or instance variable) belongs to an individual object. 14

Static Fields (cont’d) l l Static fields are stored with the class code, separately

Static Fields (cont’d) l l Static fields are stored with the class code, separately from non-static fields that describe an individual object. Public static fields, usually global constants, are referred to in other classes using “dot notation”: Class. Name. const. Name double area = Math. PI * r; set. Background(Color. blue); c. add(btn, Border. Layout. NORTH); System. out. println(area); 15

Static Fields (cont’d) l l l Usually static fields are NOT initialized in constructors

Static Fields (cont’d) l l l Usually static fields are NOT initialized in constructors (they are initialized either in declarations or in public static methods). If a class has only static fields and does not have any non-static (instance) fields, there is no point in creating objects of that class (all of them would be identical). Math and System are examples of the above. In fact, they have no public constructors and cannot be instantiated. 16

Static Methods l l l Static methods can access and manipulate a class’s static

Static Methods l l l Static methods can access and manipulate a class’s static fields. Static methods cannot access non-static fields or call non-static methods of the class. Static methods are called using “dot notation”: Class. Name. stat. Method(. . . ) double x = Math. random(); double y = Math. sqrt (x); System. exit(); 17

Instance Methods l l Non-static methods are also called instance methods. An instance method

Instance Methods l l Non-static methods are also called instance methods. An instance method is called for a particular object using “dot notation”: obj. Name. inst. Method(. . . ); l Instance methods can access ALL fields and call ALL methods of their class — both class and instance fields and methods. 18

Static (Class) vs. Non-Static (Instance) public class My. Class { public static final int

Static (Class) vs. Non-Static (Instance) public class My. Class { public static final int stat. Const; private static int stat. Var; private int inst. Var; . . . All public static int stat. Method(. . . ) { stat. Var = stat. Const; OK stat. Method 2(. . . ); inst. Var =. . . ; inst. Method(. . . ); } public int inst. Method(. . . ) { stat. Var = stat. Const; inst Var = stat. Const; OK inst. Var = stat. Method(. . . ); stat. Var = inst. Method 2(. . . ); . . . } public int inst. Method 2(. . . ) {. . . }. . . Error! Continued } 19

Static vs. Non-Static (cont’d) l Note: main is static and therefore cannot access non-static

Static vs. Non-Static (cont’d) l Note: main is static and therefore cannot access non-static fields or call non-static methods of its class: public class Hello { private String message = "Hello, World"; public static void main (String[ ] args) { System. out. println (message); } Error: non-static variable message is used in static context (main) } 20

Passing Arguments to Constructors and Methods l Any expression that has an appropriate data

Passing Arguments to Constructors and Methods l Any expression that has an appropriate data type can serve as an argument: double a = 3, b = -4; . . . Polynomial p = new Polynomial(1. 0, -(a + b), a * b); . . . double y = p. get. Value ( 2 * b - a); 21

Passing Arguments (cont’d) l int is promoted to double when necessary: . . .

Passing Arguments (cont’d) l int is promoted to double when necessary: . . . Polynomial p = new Polynomial (1, -5, 6); double y = p. get. Value ( 3 ); The same as: ( 3. 0 ) l The same as: (1. 0, -5. 0, 6. 0) A “smaller” type can be promoted to a “larger” type (e. g. , int to long, float to double). 22

Passing Arguments (cont’d) l Primitive data types are always passed “by value”: the value

Passing Arguments (cont’d) l Primitive data types are always passed “by value”: the value is copied into the parameter. double x = 3. 0; double y = p. get. Value ( x ); public class Polynomial copy {. . . public double get. Value (double u) { double v; u acts like a. . . local variable } } in get. Value x: 3. 0 y: u: 3. 0 v: 23

Passing Arguments (cont’d) l The original argument remains unchanged: public class My. Math {.

Passing Arguments (cont’d) l The original argument remains unchanged: public class My. Math {. . . public double square (double x) { x *= x; x here is a copy of the argument. The copy is return x; changed, but. . . } } My. Math calc = new My. Math(); double x = 3. 0; double y = calc. square (x); System. out. println (x + " " + y); . . . the original x is unchanged. Output: 3 9 24

Passing Objects as Arguments l Objects are always passed as references: the address is

Passing Objects as Arguments l Objects are always passed as references: the address is copied, not the object. Fraction f 1 = new Fraction (1, 2); Fraction f 2 = new Fraction (5, 17); Fraction f 3 = f 1. add (f 2); public class Fraction {. . . public Fraction add (Fraction f) { Fraction sum; . . . } } f 1: addr 1 f 2: addr 2 copy f: 5/17 addr 2 sum: 25

Passing Objects as Arguments (cont’d) l l A method can change an object passed

Passing Objects as Arguments (cont’d) l l A method can change an object passed to it as an argument (because the method gets a reference to the original object). A method can change the object for which it was called (this object acts like an implicit argument): panel. set. Backround(Color. green); 26

Passing Objects as Arguments (cont’d) l Inside a method, this refers to the object

Passing Objects as Arguments (cont’d) l Inside a method, this refers to the object for which the method was called. this can be passed to other constructors and methods as an argument: public class Chess. Game {. . . Player player 1 = new Player (this); . . . 27

return l l A method, unless void, returns a value of the specified type

return l l A method, unless void, returns a value of the specified type to the calling method. The return statement is used to immediately quit the method and return a value: return expression; The type of the return value or expression must match the method’s declared return type. 28

return (cont’d) l A method can have several return statements; then all but one

return (cont’d) l A method can have several return statements; then all but one of them must be inside an if or else (or in a switch): public some. Type my. Method (. . . ) {. . . if (. . . ) return <expression 1>; else return <expression 2>; . . . return <expression 3>; } 29

return (cont’d) l A boolean method can return true, false, or the result of

return (cont’d) l A boolean method can return true, false, or the result of a boolean expression: public boolean my. Method (. . . ) {. . . if (. . . ) return true; . . . return n % 2 == 0; } 30

return (cont’d) l A void method can use a return statement to quit the

return (cont’d) l A void method can use a return statement to quit the method early: public void my. Method (. . . ) {. . . if (. . . ) return; . . . No need } for a redundant return at the end 31

return (cont’d) l l If its return type is a class, the method returns

return (cont’d) l l If its return type is a class, the method returns a reference to an object (or null). Often the returned object is created in the method using new. For example: public Fraction inverse () { if (num == 0) return null; return new Fraction (denom, num); } l The returned object can also come from the arguments or from calls to other methods. 32

Encapsulation l l l Hiding the implementation details of a class (making all fields

Encapsulation l l l Hiding the implementation details of a class (making all fields and helper methods private) is called encapsulation. Encapsulation helps in program maintenance and team development. A class encapsulates a small set of welldefined tasks that objects of a class can perform. 33

public vs. private l l Public constructors and methods of a class constitute its

public vs. private l l Public constructors and methods of a class constitute its interface with classes that use it — its clients. All fields are usually declared private — they are hidden from clients. Static constants occasionally may be public. “Helper” methods that are needed only inside the class are declared private. 34

public vs. private (cont’d) public class My. Class { // Constructors: public My. Class

public vs. private (cont’d) public class My. Class { // Constructors: public My. Class (. . . ) {. . . }. . . // Public methods: public <sometype> my. Method (. . . ) {. . . }. . . // Private methods: private <sometype> my. Method (. . . ) {. . . }. . . // Private fields: private <sometype> my. Field; . . . } 35

public vs. private (cont’d) l A private field is open not just within the

public vs. private (cont’d) l A private field is open not just within the object but to the entire class; any object of the same class can access or even modify it. public class Fraction { private int num, denom; . . . public multiply (Fraction other) { int new. Num = num * other. num; . . . } } 36

Accessors and Modifiers l l l A programmer often provides methods, called accessors, that

Accessors and Modifiers l l l A programmer often provides methods, called accessors, that return values of private fields; methods that set values of private fields are called modifiers. Accessors’ names often start with get, and modifiers’ names often start with set. These are not precise categories: the same method can modify several fields or modify a field and also return its old or new value. 37

The Snack Bar Applet 38

The Snack Bar Applet 38

The Snack Bar Applet (cont’d) l Each Vending. Machine object has a Vendor object

The Snack Bar Applet (cont’d) l Each Vending. Machine object has a Vendor object attached to it as a private field: Your job: the Vendor class 39

Review: l l l What is the common Java style for method names? When

Review: l l l What is the common Java style for method names? When is it appropriate to define overloaded methods? Are you allowed to define a class with no constructors? Can a class have two different no-args constructors? What is a good style for naming constructors? 40

Review (cont’d): l l l Describe the difference between class and instance variables. Can

Review (cont’d): l l l Describe the difference between class and instance variables. Can non-static methods access static fields? Can static methods access instance variables? Can static methods have local variables? What is the syntax for referring to a public static field outside the class? 41

Review (cont’d): l l Are arguments of primitive data types passed to methods “by

Review (cont’d): l l Are arguments of primitive data types passed to methods “by value” or “by reference”? Can a method have more than one return statement? Can a method have no return statements? Can a method create a new object and return it to the calling method? 42

Review (cont’d): l l Define encapsulation. Are private fields of an object hidden from

Review (cont’d): l l Define encapsulation. Are private fields of an object hidden from other objects of the same class? Do public static final variables violate the encapsulation? In the Snack Bar applet, is Vendor derived from Vending. Machine or vice versa? 43