Docsity

Java Programming: Methods, Objects, and Classes (CMSC 131 Spring 2007) - Prof. Bonnie J. D, Study Guides, Projects, Research of Computer Science

Toggle sidebar
bg1
1
CMSC 131 Spring 2007
Jan Plane (adapted from Bonnie Dorr)
Lecture Set 5:
Design and Classes
This Set:
Methods and Parameter Passing
Basics of program design
Pseudo-code
Objects and classes
Heaps
Garbage Collection
More about Creating Objects and classes in Java
Methods
Constructors, Accessors, Mutators
Equality
Printing an object
CMSC 131 Spring 2007
Jan Plane (adapted from Bonnie Dorr)
1
methods:
defining and invoking
One useful type of method for this project:
defined within the FlagMaker class
invoked from within another method that is defined in the same class
we’ll do a lot more variations later
Defined based on a name and a list of parameters
public static void name(parameterlist){
body
}
Invoked by stating its name and giving an argument for each element of
the parameter list
name(argumentlist);
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

Partial preview of the text

Download Java Programming: Methods, Objects, and Classes (CMSC 131 Spring 2007) - Prof. Bonnie J. D and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

Lecture Set 5:

Design and Classes

This Set:  Methods and Parameter Passing  Basics of program design  Pseudo-code  Objects and classes  Heaps  Garbage Collection  More about Creating Objects and classes in Java  Methods  Constructors, Accessors, Mutators  Equality  Printing an object

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

1

methods:

defining and invoking

 One useful type of method for this project:

 defined within the FlagMaker class

 invoked from within another method that is defined in the same class

 we’ll do a lot more variations later

 Defined based on a name and a list of parameters

public static void name(parameterlist){

body

 Invoked by stating its name and giving an argument for each element of

the parameter list

name(argumentlist);

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

2

method information:

parameters and arguments

 parameter list

 type name for each item in the list

 e.g. (MyGrid grid, char where)

 argument list

 expression for each item in the list

 e.g. (grid, ‘t’)

 Matched between the arguments and the parameters based on position in the list

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

3

The Software Lifecycle

Requirements

Design

Coding

Testing

Deployment

Maintenance

Evolution

What customers want

What you plan to do

Your program

Did you meet requirements?

Delivery (documentation, etc.)

Bug fixes

New versions

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

6

What Is “Pseudo-code”?

 When developing a complex part of a

program (an algorithm), one of the tools often

useful is pseudo-code.

 It's not English, not programming language --

somewhere between.

 Captures the flow of the program without

worrying about language-specific details.

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

7

Example:

 Requirement: email program that allows you to send a message either to one person, or to your whole address book

 Pseudo-code:

prompt "Enter message: " input message prompt "Send to whole address book? " input answer if answer == "no“ prompt "Enter recipient: " input recipient send message to recipient otherwise for each recipient, r, in address book send message to r

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

8

What Is Pseudo-Code? (cont.)

 NOT English

 NOT a program

 Something in-between

 Captures the "logic" and "flow" of the algorithm

 Note that pseudo-code could be translated into ANY

programming language (not just Java)

 Good programming practice

 Write pseudo-code first and keep it as your design

 Include it as comments in your code to help you connect

code to design

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

9

Testing

 Some testing is done by customer (acceptance

testing)

 E.g. testing we do on your projects!

 You want to avoid errors surfacing during acceptance

testing

 How to avoid errors during acceptance testing?

 Test thoroughly before release

 Cover all cases in code (if/else branches, etc.)

 Identify “corner cases” (extreme values of inputs) and test

with these

 We will study testing more later in semester

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

12

Sample Student Object

Name Kerry Keenan

ID^444230695

DOB^ 06-22-

Major CMSC

State Methods

getAge date → age

getGrades semester^ →^ grades

etc.

etc.

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

13

Accessing State / Methods

 If  o is an object  v is an instance variable of the object  m is a method of the object  Then  o.v is how to access the data v in o  o.m is how to invoke m in o  So  System is an object, with out an instance variable  out is also an object, with println a method  System.out.println is how to access this method!  Suppose str is a String  str is an object!  Methods of this object: equals, compareTo, etc.  str.equals, str.compareTo, etc. invokes these methods on that object

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

14

Object-Oriented Programming

 Programs are collections of interacting

objects

 Writing programs involves identifying what

the objects should be and programming them

 Object-oriented languages provide features

to ease object-oriented programming

 Defining objects involves indentifying

 state

 methods

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

15

Classes

 “Blueprints” (“templates”) for objects

 Classes include specifications of

 Instance variables (including types, etc.) to include in

objects

 Implementations of methods to include in objects

 Classes can include other information also, as will

be seen later

 static methods / instance variables

 public / private methods, instance variables

 And so on

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

18

Heap = “Fresh Memory”

 While a program is running, some memory is used

to store variables

 Terminology: stack

 We have been representing stack as table, e.g.

 Rest of memory is called heap and can be used for

other purposes, including storing new objects

y 4.

x 3

Variable Value

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

19

Allocated

Heap

Main Memory

 Stack grows, shrinks

during program execution (why?)

 So does “allocated

heap” (part of heap in use)

 Unallocated part of

heap is called “free”

Heap

Stack

Free

Heap

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

20

Object Creation

 New space allocated in

heap to store instance variables

 Reference (= address)

to this space is returned

Scanner sc = new (…);

Allocated

Heap

Heap

Stack

Free

Heap

sc

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

21

Strings Are Objects

 Where is new in

String name = “Narita”;?

 Java provides it!

 String is special because it is used so often

 Java automatically “fills in” new

 You can too:

String name = new String(“Narita”);

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

24

Heap Issues

 What happens if new is called

and there is no free heap?

Crash!

 What happens if following are

executed?

String s;

s = new String(“cat");

s = new String(“dog");

s = new String(“cow");

 Wasted heap

 “cat”, “dog” no longer

referenced by stack

 Crashes become a problem!

Stack Heap

s

“cat” “dog” “cow”

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

25

Garbage Collection

 This “heap management” or “memory

management” issue is central in CS

 Java copes by invoking garbage collector to

reclaim unused but still-allocated heap space

 Garbage collector reclaims memory in

allocated heap and returns it to free heap

 In previous example, “cat” and “dog” would

be reclaimed

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

26

Stack

a

b

Example

String a = new String (“abc”);

String b = new String (“abc”);

if (a == b) {

println (“Equal”);

} else {

println (“Not equal”);

 Not equal is printed

Heap

“abc” “abc”

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

27

Stack Heap

a

b

Contrasting Example

String a = new String (“abc”);

String b = a;

if (a == b){

println (“Equal”);

} else {

println (“Not equal”);

}

 Equal is printed

 This is called ALIASING: Two variables

refer to same object.

 Can be DANGEROUS!!

 What if we really want to make a copy?

String a = "abc" String b = new String(a);

“abc”

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

30

Anatomy of an Instance

Variable Declaration

public int IDNum;

Visibility modifier Normal variable ceclaration

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

31

… for methods that do not return values

public void acceptTokens ( int tokensPassedIn){

tokenLevel = tokenLevel + tokensPassedIn;

}

Anatomy of a Method

Declaration (1)

Visibility modifier

void keyword

method name parameter list

body

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

32

Anatomy of a Method

Declaration (2)

… for methods that return values

public int lastFour (){

… return id % 10000;

}

Visibility modifier

return type

method name parameter list

body

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

33

Return Type

 Methods that return values must specify the

type of the value to be returned

 The bodies of these methods use return to

indicate when a value is to be returned

 The value being returned must have the

same type as the return type

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

36

Equality Testing

  • Need to defined what it means for two students to be equal

public boolean equals (Student otherStudent) {

if (otherStudent == NULL){ return false; }else if (id == otherStudent.id ){ return true; }else{ return false; } }

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

37

Objects to Strings

 What happens if we try to print a Student

object?

 invoke println using a Student object as an argument?

Student s1 = new Student ();

System.out.println (s1);

 Something like this prints:

Student@82ba

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

38

Java Knows “How” To Print

Any Object

 Why?

 Every class has a default toString method

 toString converts objects into strings

 System.out.println calls this method to print an object

 Default: object type and address

 toString can be overridden!

// The method for converting Students to strings

public String toString () {

return (name + “: ” + id);

CMSC 131 Spring 2007 Jan Plane (adapted from Bonnie Dorr)

39

Static Data Members and

Static Methods

 Not contained in or associated with an object

of that type

 Accessed by the ClassName.variableName

or by ClassName.methodName

 rather than by objectName.variableName or

by objectName.methodName