Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

55
Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods

Transcript of Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Page 1: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Programming for Geographical Information Analysis:

Core Skills

Lecture 4: Program Flow IIMethods

Page 2: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

ReviewTo make a variable we make the label in memory, then attach something to it.

We can make an object variable using a particular class: ClassName objectName = new ClassName();

We can access code inside an object using the dot operator:

objectName.variable = 10;double x = objectName.variable;

But how do we run code in other classes?

Page 3: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Running code

We already have!

System.out.println("Hello World");

This is running the code called “println()”.Not only does this run code, but it seems to send the code some data (“Hello World”) which it does something with.Note that we tell code from variables because code is always followed by parentheses, even if there is no data involved.

Why and how would we do this?

Page 4: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Why1) We divide code between classes to match a key idea in Object

Orientated design: Encapsulation. One aspect of this is that data and the code to work on it should be in the same class so they are easily added or replaced. Classes should deal with just one thing. This means we must have some way of running code in other classes.

2) Within a class we want to separate the code into different functional units:

a) enhances encapsulation by providing toolkits of code to deal with specific data;

b) easier to maintain; c) easier to check.

3) Also means that if we want to repeat code in different places (where a loop wouldn’t help), we can just call the chunk of code.

Page 5: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

How?

Such a chunk of code is called a method.

We’ve already used one:System.out.println("Hello World");

And, more surprisingly, we’ve already written one ourselves, the ‘main’ method:public static void main (String args[]) {

}

Page 6: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

This lecture

MethodsProtecting variables with methodsClasses and methods

Page 7: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Code structure

Almost all of the code in classes must be within methods.

Methods cannot be nested (easily).

Code runs by processing a series of methods.

Each method is called by another method in turn, or, in the case of user interaction, by methods in the JVM.

Processing can’t magically skip to methods that aren’t called – calling methods is the only thing that structures the code execution at this scale – if you want a method to run, you have to call it from somewhere.

Page 8: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Example use

public class HelloWorld {

public static void main (String args[]) {

System.out.println(“Hello World”);

}

}

This calls the println method and runs it.The println method almost certainly calls other methods inside other classes we didn’t write in order to do its job.(don’t worry about these classes for the moment – you get these invisibly and for free with the java language, like System)Processing cascades through the program by methods calling other methods in other classes.

Page 9: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Example methodpublic class Point {

double x = 0.0;

void incrementX() {

x++;

}

}

“void incrementX()” is the method declaration.Variable names are lower-case starting camelCase. We’ll come back to “void”.

Note that variables set up when this class is turned into an instance (i.e. an object) are the only running code outside of methods. This means their scope is throughout the code, including the method.

Page 10: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Using our examplepublic class PointUser {

public static void main (String[]args) {

Point pt1 = new Point();

pt1.incrementX();

}

}

“pt1.incrementX();” is the method call.Note that you can tell a method from a variable as methods are always followed by parentheses. Note that we usually have to make an object to use either variables or methods inside them (we’ll come back to System).Note that the x variable within the pt1 object is created when it is instantiated.

Page 11: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Code structuringClasses are composed of instance variables and one or more sets of unnested methods:

public class Point {

double x = 0.0;

double y = 0.0;

void incrementX {

x++;

}

void incrementY {

y++;

}

}

Page 12: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Methods

Methods are like tools in a toolkit.

In addition to just running code, as here, they can also take in and return data.

In previous slides, “void” in the declaration means nothing is returned.

Page 13: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Return valuespublic class Point {

double x = 0.0;

boolean isXGreaterThanZero() {

if (x > 0) {

return true;

} else {

return false;

}

}

}

The return type of the method must match the thing returned. All paths through the method must return something, or the

compiler will complain.

Page 14: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Example use

public class PointUser {public static void main (String[] args) {

Point pt1 = new Point();boolean answer;answer = pt1.isXGreaterThanZero();

}}

Page 15: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Good returns

Because something is being returned, you have to do something with it:

Attach a label for later use:boolean answer = pt1.isXGreaterThanZero();

System.out.println(answer);

Use the data immediately:if (pt1.isXGreaterThanZero()) {

or

System.out.println(pt1.isXGreaterThanZero());

Page 16: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Bad returns

But don’t leave it hanging in mid-air:

Point pt1 = new Point();pt1.isXGreaterThanZero();

The computer just sees this as:

Point pt1 = new Point();false;

or whatever value it is. This isn’t code, it means nothing.

Page 17: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Passing data in

You can also pass data in to be used or worked on:

public class Point {

double x = 0.0;

void addToX(double value) {

x = x + value;

}

}

Note that double value is making a label that we attach to the number passed in.

Page 18: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Example use

public class PointUser {public static void main (String[] args) {

Point pt1 = new Point();pt1.addToX(10.0);

}}

Note that we’re not getting anything back here. The return type was void.

Page 19: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Multiple values

We can pass in multiple values, and of different types:

void addToX(double value1, int value2) {

x = x + value1 + value2;

}

Use:pt1.addToX(10.0, 20);

Page 20: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Parameters and arguments

Note that the arguments sent in are allocated to the parameter variables in order.Types must match up.

pt1.addToX(10.0, 20);

void setData (double value1, int value2) {

Page 21: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

All together now

You can get methods that return or take in nothing.

You can get methods that return but take in nothing.

You can get methods that take in, but don’t return.

You can get methods that take in and return.

Page 22: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Receiving and returningpublic class Point {

double x = 0.0;

boolean isXGreaterThan (double value) {

if (x > value) {

return true;

} else {

return false;

}

}

}

Page 23: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Example usepublic class PointUser {public static void main (String[] args) {

Point pt1 = new Point();boolean answer =

pt1.isXGreaterThan(10.0);

}}

Note that while we can take in multiple things we can only return one thing.

Page 24: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Object arguments

There’s nothing to stop objects as arguments / returns:

pt2.x = 100.0;

Point pt3 = pt1.calcHalfWayTo(pt2);

Point calcHalfWayTo (Point pointIn){

double distBetween = (x – pointIn.x);

Point halfWay = new Point();

halfWay.x = x + (distBetween / 2.0);

return halfWay;

}

Page 25: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Array argumentsThere’s nothing to stop arrays as arguments / returns:

int[][] ans = pt1.addXToIntArray(intArray);

int[][] addXToIntArray (int[][] arrayIn){

int [][] temp =

new int[arrayIn.length][arrayIn[0].length];

for (int i = 0; i < arrayIn.length; i++) {

for (int j = 0; j < arrayIn[i].length; j++) {

temp[i][j] = arrayIn[i][j] + x;

}

}

return temp;

}

Page 26: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Assignment to variablesint a = 10;

int b = someObject.change(a);

System.out.println("a = " + a);

System.out.println("b = " + b);

int change (int c) {

c = 20;

return c;

}

Prints:

a = 10b = 20

Even though it looks like the value “a” points at has change, actually “c” gets a copy of the value.

Page 27: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Assignment to variablesobjectA.x = 10;

objectB = someObject.change(objectA);

System.out.println("objectA.x = " + objectA.x);

System.out.println(“objectB.x = " + objectB.x);

SomeClass change (SomeClass objectC)

{

objectC.x = 20;

return objectC;

}

Prints:

objectA.x = 20objectB.x = 20

Here, the value does change, everywhere.

Page 28: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

PolymorphismHaving methods that take in multiple types.Implemented through overloading.You can call methods that do similar things the same name. The JVM will decide which is to be used on the basis of what is passed in.

System.out.println("2");

System.out.println(2);

System.out.println(false);

All called using System.out.println(someThing)Note that if a method doesn’t exist, the JVM will try an implicit cast. If this fails you’ll get an error.

Page 29: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

This lecture

Methods

Protecting variables with methodsClasses and methods

Page 30: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Encapsulation

The variable passing in methods is set up so you don’t need to know what other people have called the variable in their classes to use them.

System.out.println(someString);

You don’t need to know the variable the someString value is placed in – the label is just added inside System.out.

This is another key element of encapsulation: you don’t need to know what goes on inside classes you use.

Page 31: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Accessor and Mutator methods

You can refer to object’s variables directly…Point p1 = new Point()

p1.x = 10.0;

However, it is good practice to use a method to get and set other object’s variables…

p1.setX (10.0);

double x1 = p1.getX();

Page 32: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Accessor Methods

Get a variable from an Object

PointUser

Point pt1 = new Point();double x1 = pt1.getX();

Point

double x = 20.0;double getX () {

return x;}

Page 33: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Mutator Methods

Set a variable in an object

PointUser

Point pt1 = new Point();pt1.setX(222.2);

Point

double x = 0.0;void setX (double xIn) {

x = xIn;}

Page 34: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Togetherpublic class Point {

double x = 0.0;

void setX (double xIn) {

x = xIn;

}

double getX() {

return x;

}

}

Page 35: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Scopepublic class Point {

double x = 0.0;

void setX (double xIn) {

x = xIn;

}

double getX() {

return x;

}

void someMethod () {

double a = 10.0;

}

}

Instance variable(because it lasts as long as this object is an instance of the class)

Parameter variable

Method variable

Page 36: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

this keyword

What if you use the same name?

public class Point{

double x = 200.0;

void setX (double x) {

this.x = x;

}

}

Page 37: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Access

It’s fine for encapsulation to demand this, but how do we enforce it?

Access modifier keywords:public usable by anyone;protectedusable by classes that inherit;private only useable by the object.

Default is code can be seen only in same directory (package).

Page 38: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Variable accesspublic class Point {

private double x = 0.0;

public void setX (double xIn) {

x = xIn;

}

public double getX() {

return x;

}

}

Page 39: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Variable access

If variables are declare final they can’t be altered.Such variables are known as ‘constants’ in other languages.Conventionally in uppercase and underscores, e.g.:

// 10 year dollar average per kilo final int PRICE_OF_GOLD = 10100;

final int PRICE_OF_SILVER = 202;

final int PRICE_OF_BEER = 4;

Page 40: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Review

Get used to assuming any variable you want another class to interact with has ‘set’ and ‘get’ mutator and accessor methods.

Always make these public (or protected) and the variables private.

Page 41: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

This lecture

Methods

Protecting variables with methods

Classes and methods

Page 42: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

The story so far…

Classes act as photocopy originals from which we make objects.

The most important class is the one we pass to the interpreter. It must have a ‘main’ method.

To make a variable we make the label in memory, then stuff something in it.

We can make an object variable using a particular class: ClassName objectName = new ClassName();

Page 43: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Referring to methods

So far the methods have been outside our class.If they are in the same class, you don’t need an object:

public class A {

void method1() {

method2();

}

void method2() {

System.out.println("done");

}

}

Page 44: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

ConstructorsSpecial method for setting up objects. Method calls aren’t very efficient, so we want to minimise them within reason.Usually first method in any class. If they’re not there (we haven’t made any so far), the compiler makes them.

public class Point {

double x = 0.0;

public Point () {

x = 10.0;

}

}

Return an object of that type and have no name (or have no name, and implicitly return that type)Called when we make a new object:

Point pointObject = new Point ();

Page 45: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Constructors

Constructors are super useful for cutting out unnecessary method calls.

Page 46: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Constructors

Nothing to stop us passing stuff in if we write the constructor to take it.

public class Point {

double x = 0.0;

public Point (double xIn) {

x = xIn;

}

}

When we make a new object:Point pointObject = new Point (10.0);

Page 47: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Polymorphism: constructors

The constructor can be overloaded to set variables differently.public class Point {

int x; int y;public Point () {

x = 10.0; y = 20.0;

} public Point (int startX, int startY) {

x = startX; y = startY;

}}

Called thus…Point point1 = new Point();

or Point point2 = new Point(23, 42);

Page 48: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Static

Note that generally we have to make objects in order to use their variables / methods.

But this isn’t always the case. Some methods and objects can be used without creating them directly:

System.out;

Page 49: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Static

These were set up with the static keyword:

public static PrintStream out;

Static variables/methods are used directly from the class.

There is one copy that can be used anywhere. Change static variables in one object, and the variable changes in all.

Static methods can only use other static variables and methods.

Page 50: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Static examples

Static methods are commonly used to make toolkits.

For example, the System class, and the Math class:double randomNumber = Math.random();

double ans = Math.sqrt(9);

These often also contain variables set as final and static, so they can be used without objects, but can’t be changed:Math.PI

Page 51: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Main

We can now understand the main declaration:public static void main (String args[])

public so the JVM can use it.

static so it can work without an object being made.

void it returns nothing.

String args[] it takes in an array of Strings.

Page 52: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

String args[]

For command line arguments:

Takes in a String array and calls it ‘args’. i.e., you can start the program like this…

> java programName hi little program –10

args[0] == “hi”args[1] == “little”args[2] == “program” args[3] == “-10”

Page 53: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Main issuesMain’s static nature cause problems. It is usual to avoid this by doing everything in the main class in

a constructor:

public class PointUser {

public PointUser () {

// Stuff done here.

}

public static void main (String[] args) {

PointUser ptUsr = new PointUser();

// or just ‘new PointUser ();’

}

}

Page 54: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

Reviewpublic class Point {

private double x = 0.0;

public void setX (double xIn) {

x = xIn;

}

public double getX() {

return x;

}

}

Page 55: Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.

ReviewStatic methods can be used straight from the class.Final variables can’t be altered.

Best way to avoid the issues with main being static is:public class PointUser {

public PointUser() {

Point p = new Point();

p.setX(10.0);

double answer = p.getX();

}

public static void main (String[] args) {

new PointUser();

}

}

Returned values must always be used.