Lecture 10: Object Oriented Programming Tami Meredith.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Kernighan/Ritchie: Kelley/Pohl:
CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
Chapter 4: Writing Classes
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Road Map Introduction to object oriented programming. Classes
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing 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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
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.
Introduction to Java Java Translation Program Structure
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Introduction Chapter 1 8/31 & 9/1 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Working With Objects Tonga Institute of Higher Education.
CSC 212 Object-Oriented Programming and Java Part 2.
Lecture 8: Bits and Pieces Tami Meredith. Roadmap Today's lecture has a bit of everything. Going back over previous chapters and pulling out little bits.
Lecture 6: Midterm Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Lecture 2: 1226 Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Lecture 12: Final Review Tami Meredith. Programming Requires 1. Identification of the problem Understanding it, identifying correct solutions 2. Solving.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Lecture 3: Branching Tami Meredith. Roadmap Brief Review of last class OOP and Methods: using the library procedures Strings Revisited: A useful Class/Data.
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
Lecture 3: Methods, Classes, and Objects Tami Meredith.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
Lecture 7: Arrays Tami Meredith. Roadmap Variables Arrays Array indices & Using arrays Array size versus length Two dimensional arrays Sorting an array.
Methods Awesomeness!!!. Methods Methods give a name to a section of code Methods give a name to a section of code Methods have a number of important uses.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Lecture 5: Methods Tami Meredith. Roadmap The new material this week is predominantly from Chapter 5 (and Section 6.2 on static ) You should try and read.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
OOP Basics Classes & Methods (c) IDMS/SQL News
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Eastside Robotics Alliance / Newport Robotics Group 1 T/Th, 6:30 – 8:30 PM Big Picture School Day 3 · 10/9/2014.
CompSci 230 S Programming Techniques
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Introduction to Computer Science / Procedural – 67130
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Java Programming Language
Classes, Objects and Methods
Presentation transcript:

Lecture 10: Object Oriented Programming Tami Meredith

Roadmap Some review A little bit on Chapter 5 (classes and objects) Overloading Most of today's material is important to understanding methods Plenty of exercises for your enjoyment

Exercise Write a method called firstNeg that takes an array of integers as its parameter. The method returns the index value of the first negative number in the array. Return -1 if the array does not contain any negative values.

Solution public static int firstNeg (int[] data) { for (int i = 0; i < data.length; i++) { if (data[i] < 0) return (i); } return (-1); }

Methods Methods can be viewed as named blocks of code Just like building with Lego, we build a program using smaller blocks 1. Takes input (via parameters) 2. Does something to the input (in the code block) 3. Creates output (a return value) A method can be named anything, but its best to select a name that is descriptive of what the method actually does

Input and Output Methods have input and output: Input to a method comes from the arguments stored in the parameters Output from a method is by way of its return value Do not confuse the data flow (in/out) of a method with USER input and output Thus: A program has input and output (from the user) A method has input and output (from other methods)

Example // grades[] -> { } -> double // Parameters -> body -> return value public static double average(int[] grades) { double sum; for (int i = 0; i < grades.length; i++) { sum = sum + ((double) grades[i]); } return (sum/((double) grades.length)); }

Return Values - Examples public static int two () { return(1); // ends method, causes 1 to be returned return(2); // NEVER EVER EXECUTED, "Dead Code" } public static int three () { // Poor style, inaccurate name return (4); } public static int four () { return (3.0); // ERROR – not an int } public static int minus2 (int x) { // x -> minus2() -> x-2 0 if (x > 2) { return (x – 2); } else { return (0); } // return ((x > 2) ? (x -2) : 0); }

Calling Methods Methods are "called" (used) when we want to execute the code in their block 1. Parameters are replaced with provided values (i.e., the arguments) 2. Block is executed 3. Return value is generated (if not void ) 4. Control flow jumps to the statement AFTER the call when the method finishes and returns 5. Return value "replaces" the method call

A call from main public static int half (int a) { return (a/2); } public static void main (String[] args){ int x = 3; // a in half is assigned value of x // y is assigned the return value of half int y = half(x); System.out.println(x + "/2 = " + y); }

Main Is just another method main is automatically called by the JVM when the program begins Provides a known starting point for execution Takes an array of strings as input Don't worry about these, the array is usually empty Can name this array args, arguments, a, fred, boffo, betty_davis, theDude,... Whatever we want! Returns type void – nothing, no return value This is because the program exits when main is done, so there is nowhere to send the return value

Grouping and Naming Arrays create groups of variables E.g., int[] data = new int[10]; creates a group of 10 integers named data Blocks create groups of statements A method is a named block of statements Classes create groups of methods All classes have a name The name of a class matches the name of the file that stores it

public class myCode { /* Define a method to print something */ public static void printname () { System.out.println("My name is Tami."); } // end printname() /* Define a method that returns something */ public static int makezero () { return (0); } // end makezero() /* Define the method main for the program */ public static void main (String[] args) { int zero; /* Use the methods we defined */ printname(); zero = makezero(); System.out.println("makezero returns " + zero); } // end main() } // end class myCode

A Hierarchy method printName class myCode File: myCode.jav a method makeZero method main statement

Types int[] data = new int[10]; Scanner keyboard = new Scanner(System.in); data is a variable of type int[] keyboard is a variable of type Scanner Scanner is a library class A class is a type!

Instantiation Instantiation is when we define an instance of a type int x; instantiates x as a variable of type int We must instantiate classes as well Classes are instantiated using the keyword new Thus Scanner keyboard = new Scanner(System.in); Instantiates keyboard as a variable of type Scanner new makes a new copy of Scanner and stores the location of that copy into keyboard

Object Types (Summary) A "class" is the "type" of an object An "object" is an instance of the class/type Scanner user = new Scanner(System.in); 1. Scanner is a (non-static) library class 2. The variable user is an instance of the class Scanner 3. user is of type Scanner

Exercise Write a method called sameChar that takes two characters as parameters. The method returns true if the characters are the same and false if they are different. Note that this method considers 'a' and 'A' as the same! (i.e., the method is case insensitive)

Solution public static boolean sameChar (char c1, char c2) { if (c1 == c2) return (true); if (('A' <= c1) && (c1 <= 'Z')) return ((c1 + 32) == c2); if (('A' <= c2) && (c2 <= 'Z')) return ((c2 + 32) == c1); return (false); }

The JVM When we run a program, the JVM instantiates: the class containing main the System class the Math class the Runtime class We have not had to instantiate these classes because it is done for us, but IT IS DONE! When the JVM instantiates main, it provides the argument (of type String[] ) to the parameter args

Classes Until now, static has prevented us from using a class as anything more than something to group the static methods that main calls Classes group methods (as we have seen) Classes however do a whole lot more! Object oriented programming (OOP) relieves heavily on classes Lets see what a class really is supposed to be...

Grouping Data and Methods public class powers { public static final int COUNT = 32; public static int times2 (int x) { return (2 * x); } // end times2 public static void main (String[] args) { int[] pow2 = new int[COUNT]; pow2[0] = 1; // 2^0 = 1 for (int i = 1; i < COUNT; i++) { pow2[i] = times2(pow2[i-1]); } } // end main() } // end class powers

Exercise... something easy Write a method that counts, and returns, how many even numbers are in an array of integers that is passed as an argument You may assume that the array uses all its elements

Solution public static int countEvens (int[] data) { int count = 0; for (int i = 0; i < data.length; i++) { if ((data[i] % 2) == 0) { count++; } return (count); } // end countEvens()

Static – Yet again Static means not-dynamic – static methods do not move in memory, because there is only one copy There is ONLY one copy of any static method or variable This is a special behaviour that we have been using We can also have non-static methods for which there is MORE than one copy!

Object Oriented Programming A class can model something For example, we can have a class for a bank account, a book chapter, a student in a course, and so on A class can group methods and data Every class must be in its own file The methods work on the data in the file We can have more than one copy of a class Instantiating the class gives us a copy of everything that is not static

Defining a class... public class student { // instance variables, only seen in class String name; int anum; // methods public void display() { System.out.println("Name: " + name); }

Using a Class public class motown { public static void main (String[] args) { student s1, s2; s1 = new student(); s2 = new student(); s1.name = "Marvin Gaye"; s1.anum = 1; s2.name = "Diana Ross"; s2.anum = 2; s1.display(); s2.display(); } // end main } // end class motown

Our program now motown.java class motown class System (has) out class PrintWriter method main (has) s1, s2 method println student.java class student method display method display Java Library

Our Manifest File: motown Contains: main() method Instantiates: Student as s1 and s2 (2 COPIES of Student ) Calls s1.display() and s2.display() >> DIFFERENT copies of display() are used! >> Each display() accesses its OWN data File: student Contains: display() method Contains: name field (type String ) Contains: anum field (type int )

Instance vs. Class Variables Class variables (and methods) there is only one copy of a class variable class variables are declared as static all instances of the class share the data in the variable static means shared class variables/methods are accessed using the name of the class Instance variables (and methods) there are multiple copies of instance variables every instance of the class has its own copy of the variables every instance of the class had its own data stored in its instance variables instance variables are not shared instance variables/methods are accessed using the (variable) name of the instance

Strings and Arrays Strings are instances (objects) of the class String Strings are used so much that they are a special class with different rules Arrays are also (secretly) classes, but this is hidden Arrays are also given special rules because they are used so much Strings and arrays have a history in other languages before OOP was invented (which is why they are also treated differently)

New (revisited) int x; // A simple integer x = 5; int[] a; // An array of integers a = new int[5]; a[0] = 22; student s; // An instance of type student s = new student(); s.name = "Super Star";

Constructors new assigns memory space new also runs the "constructor" A constructor is a special method with the same name as the class The constructor is used to (construct or) "set up" the class Constructors can take parameters

Adding a constructor public class student { // instance variables, only seen in class String name; int anum; // constructor – same name as the class student (String n) { name = n; } // other methods public void display() { System.out.println("Name: " + name); }

Using our constructor public class motown { public static void main (String[] a) { student s1, s2; s1 = new student("Marvin Gaye"); s2 = new student("Diana Ross"); //s1.name = "Marvin Gaye"; s1.anum = 1; //s2.name = "Diana Ross"; s2.anum = 2; s1.display(); s2.display(); } // end main } // end class motown

Exercise – To clear your head Write a method that reverses a String – the method should return a copy of its parameter, that has been reversed

Solution public static String reverse (String s) { String r = ""; for (int i = s.length() – 1; i >= 0; i--) { r = r + s.charAt(i); } return(r); } // end reverse()

Method Types Everything in Java has a type Even methods have a type method: arguments → return-type main: String[] → void println: String → void +: (int, int) → int

Overloading Sometimes there are two or more methods with the SAME NAME but DIFFERENT TYPES The type is used to determine which method to use E.g., + has the types (int, int) → int, (float, float) → float (String, String) → String The context of use determines which + we apply If the arguments are Strings we apply the concatenation version, if the arguments are ints we apply the integer addition version If two + methods exist with the same name, their type HAS to differ We say the method name is overloaded

Overload Resolution When we use an overloaded method (one with more than one type) we must do overload resolution to decide which method to use The types MUST differ in the parameters The types may also differ in the return value It is the parameters that are used to determine which method to apply

Example public static float half (int val) { return (((float) val) / 2.0f); } public static float half (float val) { return (val / 2.0f); } public static String half (String val) { return (val.substring(0,val.length/2)); }

Overloading and Coercion +: (int, int) → int, (float, float) → float If we have , which + do we use? Coercion is applied BEFORE overload resolution occurs Can cause very unexpected results or cause the wrong method to be used As we said earlier, PREVENT COERCION, CAST MANUALLY to ensure we get the result we desire

Overloading is GOOD! public static void println (int[] data) { System.out.print("["); for (int i = 0; i < data.length; i++) { System.out.print(data[i]); if (i != (data.length-1)) System.out.print(", "); } System.out.println("]"); } We don't need to remember the method's name!

Even better... public static void println (int[] data) { print(data); System.out.println(""); } public static void print (int[] data) { System.out.print("["); for (int i = 0; i < data.length; i++) { System.out.print(data[i]); if (i != (data.length-1)) System.out.print(", "); } System.out.print("]"); }

Exercise Write a method to turn a string into an integer E.g.: "10342" into the integer Do not worry about converting empty strings

Solution public static int toInteger (String s) { int i, result = 0; for (i = 0; i < s.length(); i++) { result = (10*result) + (s.charAt(i) – '0'); } return (result); }

From small parts come great things...

To Do Go to the lab and complete Assignment 9 Re-read Chapters 5 and 6 – they should make a lot more sense now At this point you should understand almost all of Chapters 1-7 (except the graphics supplements) and a few parts of chapter 6 The next class is mostly on programming – methodology and techniques – we will just be using material we know