36
Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

Embed Size (px)

Citation preview

Page 1: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

Introduction To Scientific Programming

Chapter 5 – More About Objects and Methods

Page 2: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 2

Overview – More, More, More !

I. More on MethodsA. ReferencingB. Static Methods (and Variables)C. Overloading

II. More on ClassesA. Wrapper ClassesB. ConstructorsC. Groups of Classes - Packages

III. More on Software DesignA. Top-Down DesignB. Using Methods: Main/Helper/Class Interface

Page 3: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 3

I. More On Methods - Referencing

What are the possibilities? Reference a method outside of its’ class Reference a method from inside its’ class

Also must consider lifetime: Reference a method before a class object has been

created Reference a method after a class object has been

created

Page 4: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 4

Public methods called outside and after an object definition has occurred simply require the object name to precede the method name.

For example://Define object myOracle

Oracle myOracle = new Oracle();

...

//dialog is a method defined in Oracle class

myOracle.dialog();

...

When an Object Name Is Required

Page 5: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 5

When An Object Name Is Not Required

What if you want to use another method within the same class? You would need objectName, but it doesn’t exist yet. Answer: this. refers to the object that contains the

current reference. Essentially, this. stands in for the object name.

You may either use this. , or omit it, since it is presumed – i.e. methods called within an class definition file do not need to reference itself.

Page 6: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 6

Class Method Reference Example

public class AddressBook{ private final int MAX_ENTRIES = 100; //Fixed size limit of 100 private String BookName; private int numberOfEntries;…

//--------------------------------------------------------------------------- // Method to find and display an entry in address book. //--------------------------------------------------------------------------- public boolean emptyBook() { if (this.numberOfEntries == 0) then //this. is optional return true; else return false; } //--------------------------------------------------------------------------- // 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++) { If !(emptybook) then //this. not used, o.k.! … } }}

Page 7: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 7

I.-B. Static Methods You’ve thought/seen that some methods don't need an

object to do their job: Ex. a method to calculate the area of a circle of radius r You should just pass the required parameter and return the area!

This is accomplished by using a static method. These methods are also called class methods.

Use the className that contains the method instead of an objectName to invoke it. Ex. Math.pow(x,3)

Declare static methods with the static modifier. Ex:

public static double area(double radius) ...

Page 8: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 8

Uses for Static Methods Static methods are commonly used to provide

libraries of useful and related methods.

It is good practice to group static methods together, when possible.

Examples: the Math class provided with Java

methods include pow, sqrt, max, min, etc. the SavitchIn class for console Input

not automatically provided with Java methods include readLineInt, readLineDouble, etc.

Page 9: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 9

The Matrix – Method Invocation

Static Non-Static

Within A Class

methodName this.methodName*

Outside Class

ClassName.methodName objectName.methodName

Page 10: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 10

Watch out! A static method cannot reference an instance variable from it’s class

Likewise, a static method cannot automatically reference a non-static method from its or any other class.

The only exception to above is if the static method creates an object of the class to use as a calling object.

Reconciling Static Methods and Method References

Page 11: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 11

Static Variables By default, variables are dynamic. However, you can also

create static variables with the reserved word static:

static int numberOfInvocations = 0;

May be public or private but are usually private for the same reasons instance variables are (encapsulation).

private static int numberOfInvocations = 0;

There is only one copy of a static variable and it can be accessed by any object of the class.

Can be used to let objects of the same class coordinate.

Page 12: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 12

Static Variables - II Static variables defined at the class level are called

Class variables.

If the variable is public, it can be referenced outside of the class by ClassName.variableName

• Ex. Math.PI

• A public static variable at the program class level has visibility throughout the program – i.e. a global variable.

Page 13: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 13

Definition: Privacy Leaks Anytime you return an object from a method, you are

giving back an address, not a value the object is "unprotected" (usually undesirable) The object looses it’s privacy – privacy leak

This applies to any class object (custom, wrapper, etc..)

One solution is to stick to returning primitive types (int, char, double, boolean, etc.

Best solution is called cloning … temp = passedObject.clone(); // method that clones (copies) object return temp; }

Page 14: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 14

I.-C. Overloading You can have the same method name with more than

one definition within the same class!

Why do this? Same calculations, different data types Same object, different initialization conditions

Each definition must have a different “signature” This means the same name but different argument types, or

a different number of arguments, or a different ordering of argument types.

The return type is not part of the signature and cannot be used to distinguish between two methods.

Page 15: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 15

Signature A method signature is the combination of method name and

number and types of arguments, in order:

.equals(int) has a different signature than .equals(String)(same method name, different argument types)

myMethod(1) has a different signature than myMethod(1, 2)

same method name, different number of arguments

myMethod(1,1.2) different signature than myMethod(1.2,1)

(same method name and number of arguments, but different order of argument types.)

Page 16: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 16

Method Overloading Example static double max(double a, double b)

          Returns the greater of two double values.

static float max(float a, float b)           Returns the greater of two float values.

static int max(int a, int b)           Returns the greater of two int values.

static long max(long a, long b)           Returns the greater of two long values.

Page 17: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 17

It’s a Complicated World – Potential Issues with Overloading If you accidentally use the wrong data type as an

argument, you can invoke a different method.

If Java does not find a signature match, it attempts some automatic type conversions, e.g. int to double. Hence, an unwanted version of the method may execute.

Finally, you cannot have two methods that only differ in return type. This will produce an error:

public double getWeight();public float getWeight();

Page 18: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 18

II. More On Classes - Wrapper Classes Used to wrap primitive types in a class structure

All primitive types have an equivalent class

The class includes useful constants and static methods (including conversion back to primitive type)

Primitive type Class type Method to convert back

int Integer intValue()

long Long longValue()

float Float floatValue()

double Double doubleValue()

char Character charValue()

Page 19: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 19

Wrapper class example - Integer

Declare an Integer class variable:Integer n = new Integer();

Convert the value of an Integer variable to its primitive type, int:int i = n.intValue(); //intValue returns an int

Some useful Integer methods/constants:Integer.MAX_VALUE,Integer.MIN_VALUE - maximum

and minimum integer value the computer can represent

Integer.valueOf("123"),Integer.toString(123) to convert a string to an integer and visa versa

Page 20: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 20

Usage of Wrapper Classes

Wrapper Class variables contain address of value

variable declaration example:Integer n;

variable declaration & init:

Integer n = new Integer(0); assignment:

n = new Integer(5);

Primitive Type variables contain the value

variable declaration example:int n;

variable declaration & init.:int n = 0;

assignment:

n = 99;

There are some important differences in the code using wrapper classes versus primitive types

Page 21: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 21

II.-B. Constructors A constructor is a special method designed to

initialize instance variables

Automatically called when an object is created using new: Integer n = new Integer(0);

Often overloaded - more than one per class! You may have different versions to initialize all, some, or none of

the instance variables

Each constructor has a different signature (a different number or sequence of argument types)

Page 22: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 22

Defining Constructors Constructor headings have the same name as the

class and do not include any reference to a return type or void.

A constructor with no parameters is called a default constructor.

If no constructor is provided, Java automatically creates a default constructor. If any constructor is provided, then no constructors are automatically

created by the compiler

Page 23: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 23

Constructor Programming Suggestions In your custom Classes, include a constructor that

initializes all instance variables.

Also, include a constructor that has no parameters (default constructor) This overrides any automatic action by the compiler

Include overloaded versions of constructor to handle different initializations

Important note: you cannot call a constructor for an object after it is created If you want to change values of instance variables after you have

created an object, you should create a set method!

Page 24: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 24

Constructor Example - PetRecordpublic class PetRecord{ private String name; private int age; //in years private double weight; //in pounds. . . public PetRecord(String initialName) { name = initialName; age = 0; weight = 0; }

Initializes three instance variables: name from the parameter and age and weight with default initial values.

Sample use:PetRecord pet1 = new Pet("Eric");

Page 25: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 25

…public PetRecord(String initialName, int initialAge, double initialWeight){

set(initialName, initialAge, initialWeight);}……private void set(String initialName, int initialAge, double initialWeight){ name = initialName; if ((initialAge < 0) || (initialWeight < 0)) { System.out.println(“Error: …”); } else { age = initialAge; weight = initialWeight; }}

You Can Use Other Methods in a Constructor

Page 26: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 26

II.-C. Packages A package is a way to group a collection of related classes

Think of a package as a library of classes They do not have to be in the same directory as your program

The first line of each class in the package must bethe keyword package followed by the name of the package:package mystuff.utilities;

To use classes from a package in a program put an import statement at the start of the file:import mystuff.utilities.*; //all classes in directory

Page 27: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 27

A Package Name

myjava

general

utilities

AClass.java

AnotherClass.java

Classes in the package

myjava is the base path

myjava.general.utilities is a specific package name

Page 28: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 28

Package Naming Conventions Use lowercase

The package name is the pathname with subdirectory separators ("/") replaced by dots

For example, if the package is in a directory named "utilities" in directory "mystuff", the package name is:imports myjava.general.utilities;

imports myjava.general.*;

imports myjava.*;

Page 29: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 29

Adding A Custom Package Path To JCreator

Page 30: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 30

III. Software Design – “Top-Down” Program Design Step 1: Define potential objects and formulas needed

Step 2: Write a list of tasks, in pseudocode, that the program must do.

Step 3: Create a flow diagram

Step 4: For each task in the program, write a list of subtasks, in pseudocode, that the method must do.

Step 5: If you can easily write Java statements for any subtask, you are finished with that subtask.

Step 6: Repeat Steps 4. & 5. until done.

Page 31: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 31

Program Design Example – “Lab 3 Investment Account”

Step 1:

Define Class InvestmentAccount w/ attributes of a savings account: balance, interest rate, deposit, contributions… Methods include open, deposit, add interest, close, …

Step 2:

Program Greeting

Open investment account #1 w/ deposit

Open investment account #2 w/ deposit

Run investment strategy #1 & compute rate of return

Run investment strategy #1 & compute rate of return

Compute difference and declare the superior strategy

Page 32: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 32

Lab 3 Investment Account – Step 3

Program Greeting

Open Investment Accounts

Run Investment Strategy #1

Run Investment Strategy #2

If #1 > #2 Print #1 is Superior

Print #2 is Superior

End

End

Page 33: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 33

Lab 3 Investment Account – Step 4

Step 4:

Open Investment Account #1 by instantiating an InvestmentAccount object with an account name, account number, initial deposit, …

Open Investment Account #2 by instantiating an InvestmentAccount object with an account name, account number, initial deposit, …

For investment strategy #1: for each of the 12 cycles, add $500 to account and compute new balance with interest

Page 34: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 34

Programming Tip:Put A main In All Classes! A main method can be used to test all members of

any class.

It serves as test or “driver” code that can be left in a class and added to as you go.

If you change the name of your project/program to the name of just your custom class, it will execute the classes’ main method.

Otherwise, when the class is used to create objects, the main method is ignored.

Page 35: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 35

Diagnostic main Main methods in Classes are referred to as

diagnostic main methods.

Remember: Because main must be static, you can't automatically invoke non-static methods of the class.

You can however, invoke a non-static method in main if you create an object of the class.

Page 36: Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5 Slide 36

Summary – Further Additions To A Class Diagnostic main methods.

set… method to change an instance variable (complement of get… method)

equals method to define equivalent objects

clone method to copy your object to a new object

Also, don’t forget writeOutput or toString to display contents of an object.