introduction to scientific programming chapter 4 – defining classes and methods

44
Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

Upload: arline-weaver

Post on 13-Dec-2015

227 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

Introduction To Scientific Programming

Chapter 4 – Defining Classes and Methods

Page 2: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 2

OverviewI. Classes & Methods

A. ClassesB. ObjectsC. MethodsD. Variables

II. OOP - Encapsulation

III. RevisitsA. ScopeB. Pass-by-value vs. Pass-by-addressC. Object Assignment & Comparison

IV. Putting It All Together

Page 3: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 3

Motivation Wouldn’t it be very handy to have software already

available that accomplish tasks that occur frequently?

In fact, it is one of the central goals of software engineering to make software development fast, efficient, and error-free.

This is accomplished by using or reusing software components that have already been developed, debugged, and tested.

This leads us to an organizing structure that has been developed over time for most modern programming languages. In Java, this is called “Classes”.

Page 4: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 4

Software Organizational HierarchyLevel of

Organization

Primitive Data TypesPrimitive Data Types- int, double, …

Code StatementCode Statement- =, public, if, …- while, for, …

OperatorsOperators

+,-, /,%, …

ObjectObject- data + method(s)

Code blockCode block- { … }

MethodsMethods- Action or value return

Low

ClassClass- group of objects

High

PackagePackage- groups of classes

Page 5: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 5

I. Introducing Classes and Methods “Top-Down”

A. Classes

B. Objects

C. Methods

D. Variables

OOP - Encapsulation

… and then

Page 6: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 6

I.-A. Classes A class is an abstract, bundled (data + code) structure that

programmers use to accomplish frequent and/or repetitive tasks.

A class is a general blueprint for constructing specific instances of that blueprint. (In general, a Class itself does not execute).

Examples: an Automobile class, an AddressBook class, a BankAccount class, a Matrix Class, a Complex class, …

A class is made up of data and Methods (actions on the data).

When a specific copy of a class is created (or instantiated), this specific instance is called an Object.

Page 7: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 7

Example: String Class String is a class

It contains data (a sequence of characters) It contains methods that perform actions and return values

on a String type Coding convention for Classes: make first letter of name

uppercase Note: Classes are additional (non-primitive) data types!

A specific string is called a String object This is a specific instance of a class Each object inherits the structure of the class (data storage

and methods)

Page 8: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 8

Example: String Class Example: read characters typed in by user from the

keyboard and output the number of characters entered

String userInput;

System.out.println(“Are you finished?”);userInput = SavitchIn.readLine();System.out.println(userInput.length());

A String Class method

Console:Are you finished?Yes3

Page 9: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 9

Class Source Files Each Java class definition should be placed in a

separate file

Use the same name for the class and the filename, except add ".java" to the file name

Good programming practice:Start the class (and file) name with capital letter and capitalize inner words e.g. MyClass.java for the class MyClass

Put all the classes you need to run a program in the same project directory

Page 10: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 10

Java Class File Structure imports

Class Data/Variable Definitions

Class Name

Class Constructor (optional)

Method 1

Method 2

Method n

Page 11: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 11

/******************************************* * Class description * ******************************************/public class Class_Name{

<Instance variable definitions-accessible to all methods>

//Method1 definitions of the form public returnType Method_Name1(type1 parmameter1, ...) { <statements defining the method> }

//Method2 definitions of the form public returnType Method_Name2(type1 parmameter1, ...) { <statements defining the method> }

}

Summary Syntax Of A Class Definition

Page 12: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 12

Book Example: Instances of A Class

Class Name: Automobile

Data: float amount of fuel float speed String license plate

Methods (actions): increaseSpeed: stop: filltank: getfuellevel:

First Instantiation:

Object name: patsCar

amount of fuel: 10 gallons

speed: 55 miles per hour

license plate: “135 XJK”

Second Instantiation:

Object name: suesCar

amount of fuel: 14 gallons

speed: 0 miles per hour

license plate: “SUES CAR”

Third Instantiation:

Object name: ronsCar

amount of fuel: 2 gallons

speed: 75 miles per hour

license plate: “351 WLF”

Class Definition

Automobile patsCar, suesCar;Automobile ronsCar;

Source Code

Page 13: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 13

UML Class Diagrams

Automobile

fuel: doublespeed: doublelicense: String

+ increaseSpeed(double howHardPress): void+ stop(double howHardPress): void

Methods(actions)

Data

Class Name

- private+ public

Graphical notation to summarize some of the main properties of a class. UML = Universal Modelling Language.

Page 14: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 14

B. Objects

Objects are named variables that are instances of a classNote: the class is their type!

Each object has both data and methods.

Object data items are also called instance variables.

Page 15: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 15

Objects II Invoking an object’s method means to call the

method, i.e. execute the method

Invoke an object's method with the dot operator objectName.method()

Each object of a class has the same data items but can have different values

All objects of the same class have the exact same methods

Page 16: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 16

Instantiating (Creating) Objects Syntax:

ClassName instance_Name = new ClassName();

Note the keyword new

Examples that we have already used in our labs: Random generator = new Random();

DecimalFormat myFormat = new DecimalFormat("0.0000");

Public instance variables can be accessed using the dot operator: My favorites

Math.PI – the most famous constant of them all Math.E – base of natural logarithms

Page 17: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 17

C. Methods A method is a series of code statements and/or

blocks that accomplish a task.

Modern day methods are descendents of what used to be called “subroutines” or “procedures”. Methods now include the association with an object.

Two basic kinds of methods: methods that return a value void methods that do some action but don’t return a

value

Page 18: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 18

Return Type of Methods All methods require that the return type be

specified

Return types may be: a primitive data type, such as char, int, double, etc. a class, such as String, AddressBook, etc. void if no value is returned

You can use a method where it is legal to use its return type, for example the readLineInt() method of SavitchIn returns an integer, so this is legal:int next;next = SavitchIn.readLineInt();

Page 19: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 19

void Method Example The definition of a writeOutput method of Class AddressBook:

This assumes that the instance variables name, numberOfEntries, and updateDate have been defined and assigned values.

This method performs an action (writes values to the screen) but does not return a value.

//AddressBook classpublic class AddressBook(){ String name; int numberOfEntries; Date updateDate;… public void writeOutput() { System.out.println(“Book = " + name); System.out.println(“Entries = " + numberOfEntries); System.out.println(“Last updated = " + updateDate"); }}

Page 20: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 20

value Method Example Methods that return a value must execute a return statement that includes the value to return

For example:

public int count = 0; //definition section

//Method #npublic int getCount(){ return count;}

Page 21: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 21

Method and Class Naming Conventions

Use verbs to name void methods they perform an action

Use nouns to name methods that return a value they create (return) a piece of data or an object

Start class names with a capital letter

Start method names with a lower case letter

Page 22: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 22

A Very Special Method - The main Method A program written to solve a problem (rather than

define an object) is written as a class with one method, main

Invoking the class name invokes the main method

Note the structure of our lab project programs:

public class LabProject3{ public static void main(String[] args) { <statements that define the main method> }}

Page 23: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 23

Methods That Follow A Specific Structure Accessor methods—public methods that allow

instance variables to be read

Mutator methods—public methods that allow instance variables to be modified Mutator methods should always check to make sure that

changes are appropriate. Providing mutator methods is much better than making instance

variables public because a method can check to make sure that changes are appropriate.

Page 24: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 24

Passing Parameters To A Method Methods can be passed input values

Input values for methods are called parameters

Each parameter and it’s data type must be specified inside the parentheses of the method heading these are called formal parameters

The calling object must put values of the same data type, in the same order, inside the parentheses of the method name these are called arguments, or actual parameters

Page 25: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 25

Primitive Data Types as Method Parameters There are two possible forms for method input parameters:

Pass-by-value (a copy of the value is passed to method) Pass-by-address (the address of the variable is passed to

method)

Let’s look at “pass-by-value” first

For all primitive data types, when the method is called, the value of each argument is copied to its corresponding formal parameter.

Formal parameters are initialized to the values passed and are local to the method.

Argument variables are not changed by the method! the method only gets a copy of the variable's value

Page 26: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 26

Example: Parameter Passing

What is the formal parameter in the method definition? number1, number2

What is the argument in the method invocation? f1, f2

//Invocation of the method... somewhere in main...f1 = SavitchIn.readLineFloat();f2 = SavitchIn.readLineFloat();System.out.println(“Closest squared integer = " + fmult(f1,f2));…

//Definition of a method to multiply two floats and return// the closest whole number. public int fmult(float number1, float number2){ float fvalue;

fvalue = number1*number2; return Math.round(fvalue);}

Page 27: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 27

D. Variables Variables declared in a Class are instance

variables.

Instance variables are created when the object is created and destroyed when the object is no longer used (this is the concept of lifetime).

The AddressBook class has three instance variables: name, numberOfEntries and updateDate.

It is always good practice to initialize variables when declared.

Page 28: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 28

Local Variables and Blocks A block (a compound statement) is the set of statements

between a pair of matching curly braces

A variable declared inside a block is known only inside that block It is local to the block, therefore it is called a local variable When the block finishes executing, local variables disappear! References to it outside the block will cause a compile error

Further, a variable name in Java can only be declared once for a method So, although the variable does not exist outside the block, other

blocks in the same method cannot reuse the variable's name Warning: some other languages (e.g. C++) allow the variable

name to be reused outside the local block.

Page 29: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 29

More On Declaring Variables Declaring variables at the method level (outside

all blocks) makes them available within all the blocks

It is ok to declare loop counters in the Initialization field of for loops, e.g. for(int i=0; i <10; i++)… The Initialization field executes only once, when

the for loop is first entered

However, avoid declaring variables inside loops It takes time during execution to create and destroy

variables, so it is better to do it just once for loops.

Page 30: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 30

II. OOP - Encapsulation• Object Oriented Programming (OOP) is the

design of software using objects

• More than just defining objects, OOP allows us to do certain things that reduce development time, reduce errors, and improve maintainability.

• The first of these is the idea of “Encapsulation”.

• Simply stated, encapsulation is the idea that you hide all of the details of your classes from the outside “user” (so they can’t mess it up).

Page 31: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 31

Encapsulation II In Encapsulation:

Classes protect their data (all instance variables are private) Assess to data is only through methods (Accessor/Mutator)

(ex. public int getCount() ) Most methods are private (public only when necessary)

Provides a public user interface so the user knows how to use the class descriptions, parameters, and names of its public methods the user cannot see or change the implementation

Page 32: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 32

Your Book’s Encapsulation Diagram

Programmer who uses the class

Interface:• Comments• Headings of public methods• Public defined

constants

Implementation:• Private instance variables• Private constants• Private methods• Bodies of public

and private methods

A programmer who uses the class can only access the instance variables indirectly through public methods and constants.

Page 33: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 33

III.-A. Revisit:Variable Scope Let’s revisit the idea of scope for variables and

methods. First, lets look at variables.

Recall, scope is the visibility (or accessibility) of something to other parts of your code. For variables:

Defined at: Variable/Object

Class Level

public Accessible/can change inside as well as outside of class

private Accessible only within class and other class methods

Method Level Accessible only within method

Code Block Accessible only within block

Page 34: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 34

Method Scope A method’s scope is established using the

modifier public or private before the methods type Ex. public int getCount()

For methods:

Defined as: Method

public Accessible inside as well as outside of class

private Accessible only within class and by other class methods

Page 35: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 35

III.-B. Revisit: Method Parameters (Pass-by-Address) What does a Java variable hold?

It depends on the type of type, primitive type or class type

A primitive type variable holds the value of the variable

Class types are more complicated they have methods and instance variables

A class type variable holds the memory address of the object the variable does not actually hold the value of the object In general, objects do not have a single value and they also have

methods, so it does not make sense to talk about its "value"

Page 36: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 36

Class Types as Method Parameters (Pass-by-value) For object variable names used as arguments in

methods, the address (not the value) is passed!

As a result, any action taken on the formal class type parameter in the method actually changes the original variable!

Two ways to protect class parameters Don’t modify contents in a method “Clone” the formal parameter inside the method

Page 37: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 37

Example: Class Type as a Method Parameter

The method call makes otherObject an alias for s2, therefore the method acts on s2, the DemoSpecies object passed to the method!

This is unlike primitive types, where the passed variable cannot be changed.

//Class invocationAddressBook abFamily = new AddressBook(“Family", …);AddressBook abWork = new AddressBook(“Work”, …);…//Start by filling work address book with family addresses s1.makeEqual(s2);……//In class AddressBook, method definition makeEqual// that copies contents of AddressBook objectpublic void makeEqual(AddressBook otherObject){ otherObject.name = this.name; otherObject.numberOfEntries = this.numberOfEntries; otherObject.updateDate = this.updateDate; for (int i=1; i<this.numberOfEntries; i++) { <code that copies entries> } }

Page 38: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 38

Comments on Example The call to method makeEqual makes otherObject an alias for abWork.

Therefore the method changes abWork, the object passed to the method.

This is unlike primitive types, where the passed variable cannot be changed.

Use of reserved word this References the calling object

Page 39: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 39

III.-C. Revisit: Object Assignment & Comparison Now that we know that an object’s variable name holds

the address of the object, we are ready to examine assignment of objects:

This transfers the address of abFamily to abWork. The net effect is that abWork now points to abFamily.

Any information in abWork prior to this assignment is lost after the assignment!

//Class invocationAddressBook abFamily = new AddressBook(“Family", …);AddressBook abWork = new AddressBook(“Work”, …);…abWork = abFamily;

Page 40: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 40

Comparing Class Variables A class variable returns the memory address

where the start of the object is stored.

If two class variables are compared using ==, it is the addresses, not the values that are compared!

This is rarely what you want to do!

Use the class's .equals() method to compare the values of class variables.

Page 41: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 41

Example: Comparing Class Variables//User enters first stringString firstLine = SavitchIn.readLine();

//User enters second stringString secondLine = SavitchIn.readLine();…

//this compares their addressesif(firstLine == secondLine){ <body of if statement>}…

//this compares the characters in the stringsif(firstLine.equals(secondLine)//this compares their values{ <body of if statement>}

Page 42: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 42

IV. Putting It All Together – An AddressBook Class//****************************************************************************///* AddressBook.java//* //* This class represents an electronic address book that can store contact//* information. Standard actions include adding a contact, deleting a contact,//* finding a contact, and displaying a contact//*//* Author: S. Horton//* Date created: 09/05/03//****************************************************************************/////Import Date classimport java.util.Date;

////Start of class defintion//public class AddressBook{

private final int MAX_ENTRIES = 100; //Fixed size limit of 100

private String BookName; private int numberOfEntries; private Date updateDate; private String[] names = new String[MAX_ENTRIES]; private String[] phones = new String[MAX_ENTRIES];

Page 43: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 43

IV. Putting It All Together – An AddressBook Class //--------------------------------------------------------------------------- // Class constructor that sets up a new AddressBook. Input is the name of // the address book. //--------------------------------------------------------------------------- public AddressBook(String name) { BookName = name; updateDate.getTime(); numberOfEntries = 0; }

//--------------------------------------------------------------------------- // Method to add an entry to address book. //--------------------------------------------------------------------------- public void addEntry(String entryName, String workPhone) { numberOfEntries += 1; if (numberOfEntries > MAX_ENTRIES) {

numberOfEntries -= 1; System.out.println("Error: max entries="+ MAX_ENTRIES + " reached, " + "cant add entry!");

} else { names[numberOfEntries] = entryName; phones[numberOfEntries] = workPhone; updateDate.getTime(); } }

Page 44: Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

S.Horton/107/Ch. 4 Slide 44

IV. Putting It All Together – An AddressBook Class //--------------------------------------------------------------------------- // Method to delete an entry to address book. //--------------------------------------------------------------------------- public void deleteEntry(String entryName) { // Code to search names array for entryName // If found, remove it and then bubble up names to fill hole // If not found print error message } //--------------------------------------------------------------------------- // Method to find and display an entry in address book. //--------------------------------------------------------------------------- public void findEntry(String entryName) { // Code to search names array for entryName // If found, display it // If not found print error message } //--------------------------------------------------------------------------- // Method that copies contents of AddressBook object //--------------------------------------------------------------------------- public void makeEqual(AddressBook otherObject) { otherObject.BookName = this.BookName; otherObject.numberOfEntries = this.numberOfEntries; otherObject.updateDate = this.updateDate; for (int i=1; i<this.numberOfEntries; i++) { //code that copies entries } }}