Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 10: Object Oriented Programming Tami Meredith.

Similar presentations


Presentation on theme: "Lecture 10: Object Oriented Programming Tami Meredith."— Presentation transcript:

1 Lecture 10: Object Oriented Programming Tami Meredith

2 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

3 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.

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

5 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

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

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

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

9 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

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

11 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

12 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

13 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

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

15 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!

16 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

17 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

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

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

20 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

21 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...

22 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

23 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

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

25 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!

26 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

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

28 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

29 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

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

31 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

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

33 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";

34 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

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

36 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

37 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

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

39 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

40 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

41 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

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

43 Overloading and Coercion +: (int, int) → int, (float, float) → float If we have 3 + 4.0, 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

44 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!

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

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

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

48 From small parts come great things...

49 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


Download ppt "Lecture 10: Object Oriented Programming Tami Meredith."

Similar presentations


Ads by Google