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

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Static Methods Static methods are those methods that are not called on objects. In other words, they don’t have an implicit parameter. Random number generation.
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
Road Map Introduction to object oriented programming. Classes
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
Access to Names Namespaces, Scopes, Access privileges.
Enhancing classes Visibility modifiers and encapsulation revisited
Terms and Rules Professor Evan Korth New York University (All rights reserved)
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Introduction to Methods
Hello AP Computer Science!. What are some of the things that you have used computers for?
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
4.1 Instance Variables, Constructors, and Methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Session 7 Methods Strings Constructors this Inheritance.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
JAVA COURSE 1 Computer Engineering Association. Compile your first program Public class Hello{ public class Hello(){ System.out.println(“Hello”); } puclic.
Programming for Geographical Information Analysis: Core Skills Lecture 2: Storing data.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Working With Objects Tonga Institute of Higher Education.
Hello Computer Science!. Below is an example of a Hello World program in JAVA. While it is only three lines of code, there are many things that are happening.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
OOP Basics Classes & Methods (c) IDMS/SQL News
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Topic: Classes and Objects
Some Eclipse shortcuts
Chapter 3: Using Methods, Classes, and Objects
Programming Language Concepts (CIS 635)
Java LESSON 7 Objects, Part 1
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Group Status Project Status.
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object Oriented Programming in java
Java Programming Language
Classes, Objects and Methods
Visibilities and Static-ness
CMSC 202 Exceptions.
Corresponds with Chapter 5
Presentation transcript:

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

Review To 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?

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?

Why 1)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.

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[]) { }

This lecture Methods Protecting variables with methods Classes and 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.

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.

Example method public 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.

Using our example public 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.

Code structuring Classes 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++; }

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.

Return values public 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.

Example use public class PointUser { public static void main (String[] args) { Point pt1 = new Point(); boolean answer; answer = pt1.isXGreaterThanZero(); }

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());

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.

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.

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.

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);

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) {

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.

Receiving and returning public class Point { double x = 0.0; boolean isXGreaterThan (double value) { if (x > value) { return true; } else { return false; }

Example use public 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.

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; }

Array arguments There’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; }

Assignment to variables int 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 = 10 b = 20 Even though it looks like the value “ a ” points at has change, actually “ c ” gets a copy of the value.

Assignment to variables objectA.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 = 20 objectB.x = 20 Here, the value does change, everywhere.

Polymorphism Having 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.

This lecture Methods Protecting variables with methods Classes and 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.

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();

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; }

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; }

Together public class Point { double x = 0.0; void setX (double xIn) { x = xIn; } double getX() { return x; }

Scope public 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

this keyword What if you use the same name? public class Point{ double x = 200.0; void setX (double x) { this.x = x; }

Access It’s fine for encapsulation to demand this, but how do we enforce it? Access modifier keywords: public usable by anyone; protected usable by classes that inherit; private only useable by the object. Default is code can be seen only in same directory (package).

Variable access public class Point { private double x = 0.0; public void setX (double xIn) { x = xIn; } public double getX() { return x; }

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;

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.

This lecture Methods Protecting variables with methods Classes and 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();

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"); }

Constructors Special 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 ();

Constructors Constructors are super useful for cutting out unnecessary method calls.

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);

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);

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;

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.

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

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.

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”

Main issues Main’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 ();’ }

Review public class Point { private double x = 0.0; public void setX (double xIn) { x = xIn; } public double getX() { return x; }

Review Static 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.