Скачать презентацию Advanced Review Shlomo Hershkop 2007 1 Advanced Скачать презентацию Advanced Review Shlomo Hershkop 2007 1 Advanced

ce0252580ae2c48806251b581a6431ab.ppt

  • Количество слайдов: 75

Advanced Review Shlomo Hershkop 2007 1 Advanced Review Shlomo Hershkop 2007 1

Advanced Review n n Time classes Date Classes File input/output Packages Shlomo Hershkop 2007 Advanced Review n n Time classes Date Classes File input/output Packages Shlomo Hershkop 2007 2

Multiple dimensions n n n No reason cant create 4, 5, 6 dimension arrays Multiple dimensions n n n No reason cant create 4, 5, 6 dimension arrays Gets hard to manage Better idea: n n Think about another way of representing the data Often creating an object is a better approach Shlomo Hershkop 2007 3

Arrays further n n n n Need to explicitly copy contents of arrays when Arrays further n n n n Need to explicitly copy contents of arrays when resizing arrays with temp one Better solution: Array. List Vector Full object versions of arrays Capacity can grow over time Useful methods bundles with them Shlomo Hershkop 2007 4

code n Create a new class with a main called Vector. Test n Create code n Create a new class with a main called Vector. Test n Create a vector n n n Put in some stuff Print them out Replace something in the middle Print it out Clear the vector Print it out Shlomo Hershkop 2007 5

Default values n n Should be aware if you forget to set values Might Default values n n Should be aware if you forget to set values Might mess up your logic n n Think of multiplying a bunch of numbers and not setting one of them… Compiler/IDE will let you know if you forgot to set values (warning) Shlomo Hershkop 2007 6

Time n n Next lets discuss how time is handled in Java. util. Date Time n n Next lets discuss how time is handled in Java. util. Date is the way java represents a point in time It is measured in milliseconds Time = 0 what does that mean? Shlomo Hershkop 2007 7

Date n Time 0 = first millisecond in 1970 n Historical reasons for this Date n Time 0 = first millisecond in 1970 n Historical reasons for this n long is the type it uses n n n Range to +9, 223, 372, 036, 854, 775, 807 Don’t memorize that Lets look at the API n What is a deprecated method ? ? n Example: get. Day() ? ? Shlomo Hershkop 2007 8

Why Date n n n Why are we wrapping the time long number? Why Date n n n Why are we wrapping the time long number? "I'll see you on 996, 321, 998, 346. " doesn’t really work Also allows you to easily order and compare different points in time…. meaningfully Shlomo Hershkop 2007 9

Change over time (no pun) n Nothing you program should be set in stone Change over time (no pun) n Nothing you program should be set in stone n Sometimes your design changes n Need to go back and change your code n Deprecated methods are those which have been replaced…but left in place so your old stuff shouldn’t crash if you try to recompile with latest jdk Shlomo Hershkop 2007 10

Back to time n System. current. Time. Millis() Returns the current time on the Back to time n System. current. Time. Millis() Returns the current time on the system n As a Date Object n Shlomo Hershkop 2007 11

Ideas n n n Although would like to represent a point in time, usually Ideas n n n Although would like to represent a point in time, usually time is associated with other measurements Month Year Shlomo Hershkop 2007 12

The Gregorian. Calendar Class n n The Date class doesn't measure months, weekdays, etc. The Gregorian. Calendar Class n n The Date class doesn't measure months, weekdays, etc. That's the job of a calendar A calendar assigns a name to a point in time Many calendars in use: Gregorian n Contemporary: Hebrew, Arabic, Chinese n Historical: French Revolutionary, Mayan n Shlomo Hershkop 2007 13

Relationships Shlomo Hershkop 2007 14 Relationships Shlomo Hershkop 2007 14

Next step n Lets design a new class to represent a day n Today Next step n Lets design a new class to represent a day n Today is Tuesday Day today = new Day(); Today. add(1); Shlomo Hershkop 2007 //should give us Wednesday 15

Goal of Day Class n n Answer questions such as How many days are Goal of Day Class n n Answer questions such as How many days are there between now and the end of the year? What day is 100 days from now? How many days till my birthday (I’ve always wanted a _______) Shlomo Hershkop 2007 16

Designing the class n n Lets have a method days. From it computes number Designing the class n n Lets have a method days. From it computes number of days between two days: int n = today. days. From(birthday); n add. Days computes a day that is some days away from a given day: Day later = today. add. Days(999); n Mathematical relationship: d. add. Days(n). days. From(d) == n d 1. add. Days(d 2. days. From(d 1)) == d 2 Shlomo Hershkop 2007 17

n n Constructor Date(int year, int month, int date) Will need the following methods: n n Constructor Date(int year, int month, int date) Will need the following methods: get. Year n get. Month n get. Date n Shlomo Hershkop 2007 18

Implementation n Straightforward which member will need: private int year private int month private Implementation n Straightforward which member will need: private int year private int month private int date n add. Days/days. Between tedious to implement n n n April, June, September, November have 30 days February has 28 days, except in leap years it has 29 days All other months have 31 days Leap years are divisible by 4, except after 1582, years divisible by 100 but not 400 are not leap years There is no year 0; year 1 is preceded by year -1 In the switchover to the Gregorian calendar, ten days were dropped: October 15, 1582 is preceded by October 4 Shlomo Hershkop 2007 19

Day Code public Day(int a. Year, int a. Month, int a. Date) a. Year, Day Code public Day(int a. Year, int a. Month, int a. Date) a. Year, a. Month, a. Date) { year = a. Year; month = a. Month; date = a. Date; } private int int year; month; date; private static final int[] DAYS_PER_MONTH int[] = { 31, 28, 31, 30, 31 }; private static final int int GREGORIAN_START_YEAR = 1582; GREGORIAN_START_MONTH = 10; GREGORIAN_START_DAY = 15; JULIAN_END_DAY = 4; private static final int JANUARY = 1; private static final int FEBRUARY = 2; private static final int DECEMBER = 12; Shlomo Hershkop 2007 20

Day Code private Day next. Day() 112: { 113: int y = year; 114: Day Code private Day next. Day() 112: { 113: int y = year; 114: int m = month; 115: int d = date; 116: 117: if (y == GREGORIAN_START_YEAR 118: && m == GREGORIAN_START_MONTH 119: && d == JULIAN_END_DAY) 120: d = GREGORIAN_START_DAY; 121: else if (d < days. Per. Month(y, m)) days. Per. Month(y, 122: d++; 123: else 124: { 125: d = 1; 126: m++; 127: if (m > DECEMBER) 128: { 129: m = JANUARY; 130: y++; 131: if (y == 0) y++; 132: } 133: } 134: return new Day(y, m, d); Day(y, 135: } Shlomo Hershkop 2007 21

private static int days. Per. Month(int y, int m) { int days = DAYS_PER_MONTH[m private static int days. Per. Month(int y, int m) { int days = DAYS_PER_MONTH[m - 1]; if (m == FEBRUARY && is. Leap. Year(y)) days++; return days; } private static boolean is. Leap. Year(int y) { if (y % 4 != 0) return false; if (y < GREGORIAN_START_YEAR) return true; return (y % 100 != 0) || (y % 400 == 0); } Shlomo Hershkop 2007 22

Tester 01: public class Day. Tester 02: { 03: public static void main(String[] args) Tester 01: public class Day. Tester 02: { 03: public static void main(String[] args) 04: { 05: Day today = new Day(2001, 2, 3); //February 3, 2001 06: Day later = today. add. Days(999); 07: System. out. println(later. get. Year() 08: + "-" + later. get. Month() 09: + "-" + later. get. Date()); 10: System. out. println(later. days. From(today)); // Prints 999 11: } 12: } Shlomo Hershkop 2007 23

Notice n Private helper methods n Notice all the work to increment a day Notice n Private helper methods n Notice all the work to increment a day Shlomo Hershkop 2007 24

Another idea n n n This is for illustration, don’t need to code For Another idea n n n This is for illustration, don’t need to code For greater efficiency, we can use Julian day number Used in astronomy Number of days since Jan. 1, 4713 BCE May 23, 1968 = Julian Day 2, 440, 000 Greatly simplifies date arithmetic Shlomo Hershkop 2007 25

Code public Day(int a. Year, int a. Month, int a. Date) { //notice we Code public Day(int a. Year, int a. Month, int a. Date) { //notice we are calling a private //helper function julian = to. Julian(a. Year, a. Month, a. Date); } //that’s all we need private int julian; Shlomo Hershkop 2007 26

Helper function private static int to. Julian(int year, int month, int date) { int Helper function private static int to. Julian(int year, int month, int date) { int jy = year; if (year < 0) jy++; int jm = month; if (month > 2) jm++; else{ jy--; jm += 13; } int jul = (int) (java. lang. Math. floor(365. 25 * jy) + java. lang. Math. floor(30. 6001 * jm) + date + 1720995. 0); int IGREG = 15 + 31 * (10 + 12 * 1582); // Gregorian Calendar adopted Oct. 15, 1582 if (date + 31 * (month + 12 * year) >= IGREG) // Change over to Gregorian calendar { int ja = (int) (0. 01 * jy); jul += 2 - ja + (int) (0. 25 * ja); } return jul; } hlomo Shlomo Hershkop 2007 S 27

Any other ideas? n So you see that using the class doesn’t change even Any other ideas? n So you see that using the class doesn’t change even though we totally changed how the inside works n n So its easy to move up or down the calendar n n Called encapsulation Add subtract Where would it cost us ? ? Shlomo Hershkop 2007 28

Switch gears n n n Lets talk about how to use files Your program Switch gears n n n Lets talk about how to use files Your program starts in main, computes, then maybe prints out something before closing up Would be great if can save results somewhere n Hey lets use files Shlomo Hershkop 2007 29

File manipulations n Working with files n Reading files n Writing files Shlomo Hershkop File manipulations n Working with files n Reading files n Writing files Shlomo Hershkop 2007 30

Please note n One of the great things about file manipulation on java is Please note n One of the great things about file manipulation on java is that it is the same on Windows n Linux n Mac n n If done right Shlomo Hershkop 2007 31

File n Basic object is called File n File data = new File(“test. txt”); File n Basic object is called File n File data = new File(“test. txt”); n n It will look in the same directory the java file is sitting in for the test file Calling: data. get. Absolute. Path() n Will print out the local version of the full path to the file Shlomo Hershkop 2007 32

Directories n n n If your File object is a directory The list method Directories n n n If your File object is a directory The list method returns an array of String file names, list. Files returns an array of File objects Shlomo Hershkop 2007 33

limitations n n n The File object has a limited number of useful methods limitations n n n The File object has a limited number of useful methods None which can actually write something to it Need to use higher level class to work with file contents Shlomo Hershkop 2007 34

Dealing with text n n When dealing with text output/input can use Print. Writer Dealing with text n n When dealing with text output/input can use Print. Writer to write to a file Shlomo Hershkop 2007 35

code n Print. Writer pw = new Print. Writer(new File( code n Print. Writer pw = new Print. Writer(new File("Test. txt"))); n What is File. Writer ? n Lets pull up the API Shlomo Hershkop 2007 36

n n n Helper class to help make sure things are written efficiently Don’t n n n Helper class to help make sure things are written efficiently Don’t forget to close the file handle when done And flush if using a buffered handle Shlomo Hershkop 2007 37

n Ok lets write some code n Main program n n Will write a n Ok lets write some code n Main program n n Will write a 3 line poem (yes you need to write one now) to a test. txt file Notice how your have to add try catch to handle certain declared exceptions ? ? Shlomo Hershkop 2007 38

Run code n Confirm that the file has been created n Now write another Run code n Confirm that the file has been created n Now write another class to read the file Shlomo Hershkop 2007 39

n How would you adopt the reader to find something in the file ? n How would you adopt the reader to find something in the file ? ? Shlomo Hershkop 2007 40

n For each line read n Look for something n See String API for n For each line read n Look for something n See String API for helper methods n Now write the code Shlomo Hershkop 2007 41

Next up n n n Interfaces Inheritance Abstract Classes Polymorphism Generics Shlomo Hershkop 2007 Next up n n n Interfaces Inheritance Abstract Classes Polymorphism Generics Shlomo Hershkop 2007 42

Two dimensions n n You can also initialize the inner array as a separate Two dimensions n n You can also initialize the inner array as a separate call. Doesn’t have to be congruous memory locations int [][]example = new int[5][]; for (int i=0; i<5; i++){ example[i] = new int[i+1]; } Shlomo Hershkop 2007 43

Interface n n An interface is a special class that defines the behavior of Interface n n An interface is a special class that defines the behavior of other classes Example n How many mp 3 players are on the market ? Shlomo Hershkop 2007 44

Mp 3 players n No matter what type of mp 3 player you buy Mp 3 players n No matter what type of mp 3 player you buy you expect certain behavior n Play Forward(next song) Rewind(last song) Random n Think of your own n Shlomo Hershkop 2007 45

n n If I want to program a bunch of mp 3 players and n n If I want to program a bunch of mp 3 players and want to force all of them to have some minimum behavior I would encode that as an interface Here is an example: Shlomo Hershkop 2007 46

code public interface mp 3 player { public boolean play(); public boolean rewind(); public code public interface mp 3 player { public boolean play(); public boolean rewind(); public boolean forward(); public int get. Song. Count(); public boolean delete. All(); } Shlomo Hershkop 2007 47

analysis n n n Basically am defining ideas Would add comments to each what analysis n n n Basically am defining ideas Would add comments to each what they are supposed to be doing (expected behavior Then any class which wants to be nice, would agree to behave this way Shlomo Hershkop 2007 48

Code: Ipod. MP 3 n n Say we want to create a really cool Code: Ipod. MP 3 n n Say we want to create a really cool mapple ipod player Want to stick to the mp 3 behavior public class Ipodmp 3 implements mp 3 player {. . n This means that we need to define those methods for this specific class Shlomo Hershkop 2007 49

Note n n Can implement as many interfaces as you like Will notice them Note n n Can implement as many interfaces as you like Will notice them in the api when you look at the standard libraries Compiler will check and complain if you don’t implement all the methods you are promising in the interface you impliment Nothing actually checks that you are doing the correct thing…. that is up to the programmer Shlomo Hershkop 2007 50

GASP! n Question: so what does : Ipodmp 3 player 1 = new Ipodmp GASP! n Question: so what does : Ipodmp 3 player 1 = new Ipodmp 3 (); player 1. play() actually do ? ? n Answer: Maybe erase your hard drive…look at the source code Shlomo Hershkop 2007 51

Iterators n Many of the classes in Java represent a collection of items Some Iterators n Many of the classes in Java represent a collection of items Some have order Some don’t have order n All the students in one room n n Alphabetical list n Bag of names (raffle) n Shlomo Hershkop 2007 52

Two types n Here is a general Iterator idea n Get the iterator object Two types n Here is a general Iterator idea n Get the iterator object from the class n n Can ask the iterator object if it has any more stuff Get the next thing Shlomo Hershkop 2007 53

Inheritance n n You have a really useful class Want to specialize it in Inheritance n n You have a really useful class Want to specialize it in more than one way Can either copy paste a bunch of time and tweak each copy Problem if we find a bug, will need to run to all copies and fix everything Shlomo Hershkop 2007 54

Easier way: n n Look at all the classes that are related, what ideas Easier way: n n Look at all the classes that are related, what ideas do they all share Example: what is common between all kinds of cars Make that idea the base class, and each specialization a sub class Known as inheritance! Shlomo Hershkop 2007 55

Inheritance n Use the ‘extends’ keyword Allows you to reuse objects n Some issues: Inheritance n Use the ‘extends’ keyword Allows you to reuse objects n Some issues: n When do you extend? n When do you implement an interface? n Shlomo Hershkop 2007 56

Example n n n Geneal idea of an Animal Can code it as class Example n n n Geneal idea of an Animal Can code it as class Animal Then have specific code n n n class Horse extends Animal class Whale extends Animal What ever methods are the same in both would be coded in the Animal class, specific methods (number. Legs() would be defined in the specific subclass) Shlomo Hershkop 2007 57

Super constructors n n When refering to parent class (Animal) Use super keyword in Super constructors n n When refering to parent class (Animal) Use super keyword in subclass constructor: public Horse(String a. Name) { super(a. Name); // calls superclass constructor //rest of your stuff here } n n Call to super must be first statement in subclass constructor If subclass constructor doesn't call super, superclass must have constructor without parameters Shlomo Hershkop 2007 58

Polymorphism n n n This is just fancy word that tells you java will Polymorphism n n n This is just fancy word that tells you java will figure out the following code: Animal A = new Horse(“tom”); So although A is really a horse, it can be refered to by parent handle. This would be illigal: Horse A = new Whale(); Why ? Shlomo Hershkop 2007 59

Next n n Imagine you have a class which has variable members of a Next n n Imagine you have a class which has variable members of a specific type Example: Have a list of numbers, say a list of zip codes which you have sent packages in the last X months What if you want to change zip codes to Strings because you are now sending packages to canada Shlomo Hershkop 2007 60

2 solutions n Copy paste code and replace all ints with Strings n Debug 2 solutions n Copy paste code and replace all ints with Strings n Debug like crazy n …. or use Generics Shlomo Hershkop 2007 61

Basic idea n n n Tell java you are dealing with some type without Basic idea n n n Tell java you are dealing with some type without know what it is Can set some rules on it When you create an instance of the object you will tell java what you want Shlomo Hershkop 2007 62

Code public class shopping. List<T> { shopping. List<T> private Array. List<T> the. List; shopping. Code public class shopping. List { shopping. List private Array. List the. List; shopping. List(){ the. List = new Array. List(); } public void add. Item(T item){ the. List. add(item ); } public int get. Number. On. List (){ return the. List. size(); } public T get. Item. At(int location){ return the. List. get(location ); } } Shlomo Hershkop 2007 63

Code 1 //once you get previous screen running at the following method public void Code 1 //once you get previous screen running at the following method public void show. Type() { System. out. println("Type of T is " + ob. get. Class(). get. Name()); } Shlomo Hershkop 2007 64

Usage shopping. List<Integer> e 1; e 1 = new shopping. List<Integer>; e 1. add(15); Usage shopping. List e 1; e 1 = new shopping. List; e 1. add(15); int v = e 1. get. Item. At(0); Write a main to test the idea of generics Shlomo Hershkop 2007 65

Example 2 class Example 2<T, V> { T ob 1; V ob 2; Example Example 2 class Example 2 { T ob 1; V ob 2; Example 2(T o 1, V o 2) { ob 1 = o 1; ob 2 = o 2; } T getob 1() { return ob 1; } V getob 2() { return ob 2; } } Shlomo Hershkop 2007 66

Example 3 class Example 3<Q extends Number> { Q[] nums; // array of Number Example 3 class Example 3 { Q[] nums; // array of Number or subclass Stats(Q[] o) { nums = o; } double sum() { double sum = 0. 0; for(int i=0; i < nums. length; i++) sum += nums[i]. double. Value(); return sum; } } Shlomo Hershkop 2007 67

Usage Double dnums[] ={ 1. 1, 2. 2, 3. 3, 4. 4, 5. 5 Usage Double dnums[] ={ 1. 1, 2. 2, 3. 3, 4. 4, 5. 5 }; Example 3 dob = new Example 3(dnums); double w = dob. sum(); System. out. println("dob sum is " + w); Shlomo Hershkop 2007 68

class Two. D { int x, y; Two. D(int a, int b) { x class Two. D { int x, y; Two. D(int a, int b) { x = a; y = b; } } Example 4 class Three. D extends Two. D { int z; Three. D(int a, int b, int c) { super(a, b); z = c; } } class Four. D extends Three. D { int t; Four. D(int a, int b, int c, int d) { super(a, b, c); t = d; } } Shlomo Hershkop 2007 69

class Coords<T extends Two. D> { T[] coords; Coords(T[] o) { coords = o; class Coords { T[] coords; Coords(T[] o) { coords = o; } } Shlomo Hershkop 2007 70

static void show. XY(Coords<? > c) { System. out. println( static void show. XY(Coords c) { System. out. println("X Y Coordinates: "); for(int i=0; i < c. coords. length; i++) System. out. println(c. coords[i]. x + " " + c. coords[i]. y); System. out. println(); } Shlomo Hershkop 2007 71

static void show. XYZ(Coords<? extends Three. D> c) { System. out. println( static void show. XYZ(Coords c) { System. out. println("X Y Z Coordinates: "); for(int i=0; i < c. coords. length; i++) System. out. println(c. coords[i]. x + " " + c. coords[i]. y + " " + c. coords[i]. z); System. out. println(); } Shlomo Hershkop 2007 72

static void show. All(Coords<? extends Four. D> c) { System. out. println( static void show. All(Coords c) { System. out. println("X Y Z T Coordinates: "); for(int i=0; i < c. coords. length; i++) System. out. println(c. coords[i]. x + " " + c. coords[i]. y + " " + c. coords[i]. z + " " + c. coords[i]. t); System. out. println(); } Shlomo Hershkop 2007 73

Using in methods n Just learn how to read the following: static <T, V Using in methods n Just learn how to read the following: static boolean is. In(T x, V[] y) { for(int i=0; i < y. length; i++) { if(x. equals(y[i])) return true; } return false; } Shlomo Hershkop 2007 74

n Hope you had fun learning this! Shlomo Hershkop 2007 75 n Hope you had fun learning this! Shlomo Hershkop 2007 75