Shlomo Hershkop 2007Shlomo Hershkop 2007 11
Advanced ReviewAdvanced Review
Shlomo Hershkop 2007Shlomo Hershkop 2007 22
Advanced ReviewAdvanced Review
Time classesTime classes Date ClassesDate Classes File input/output File input/output PackagesPackages
Shlomo Hershkop 2007Shlomo Hershkop 2007 33
Multiple dimensionsMultiple dimensions
No reason cant create 4,5,6 No reason cant create 4,5,6 dimension arraysdimension arrays
Gets hard to manageGets hard to manage Better idea: Better idea:
Think about another way of representing Think about another way of representing the datathe data
Often creating an object is a better Often creating an object is a better approachapproach
Shlomo Hershkop 2007Shlomo Hershkop 2007 44
Arrays furtherArrays further
Need to explicitly copy contents of arrays when Need to explicitly copy contents of arrays when resizing arrays with temp oneresizing arrays with temp one
Better solution:Better solution: ArrayListArrayList VectorVector
Full object versions of arraysFull object versions of arrays Capacity can grow over timeCapacity can grow over time Useful methods bundles with themUseful methods bundles with them
Shlomo Hershkop 2007Shlomo Hershkop 2007 55
codecode
Create a new class with a main called VectorTestCreate a new class with a main called VectorTest
Create a vectorCreate a vector
Put in some stuffPut in some stuff Print them outPrint them out Replace something in the middleReplace something in the middle Print it outPrint it out Clear the vectorClear the vector Print it outPrint it out
Shlomo Hershkop 2007Shlomo Hershkop 2007 66
Default valuesDefault values
Should be aware if you forget to set Should be aware if you forget to set valuesvalues
Might mess up your logicMight mess up your logic Think of multiplying a bunch of numbers Think of multiplying a bunch of numbers
and not setting one of them…and not setting one of them… Compiler/IDE will let you know if you Compiler/IDE will let you know if you
forgot to set values (warning)forgot to set values (warning)
Shlomo Hershkop 2007Shlomo Hershkop 2007 77
TimeTime
Next lets discuss how time is handled Next lets discuss how time is handled in Javain Java
Java.util.Date is the way java Java.util.Date is the way java represents a point in timerepresents a point in time
It is measured in millisecondsIt is measured in milliseconds Time = 0 what does that mean?Time = 0 what does that mean?
Shlomo Hershkop 2007Shlomo Hershkop 2007 88
DateDate
Time 0 = first millisecond in 1970Time 0 = first millisecond in 1970 Historical reasons for thisHistorical reasons for this
long is the type it useslong is the type it uses Range to +9,223,372,036,854,775,807Range to +9,223,372,036,854,775,807 Don’t memorize thatDon’t memorize that
Lets look at the APILets look at the API What is a deprecated method ??What is a deprecated method ??
Example: getDay() ??Example: getDay() ??
Shlomo Hershkop 2007Shlomo Hershkop 2007 99
Why DateWhy Date
Why are we wrapping the time long Why are we wrapping the time long number?number?
"I'll see you on 996,321,998,346." doesn’t "I'll see you on 996,321,998,346." doesn’t really workreally work
Also allows you to easily order and compare Also allows you to easily order and compare different points in time….meaningfullydifferent points in time….meaningfully
Shlomo Hershkop 2007Shlomo Hershkop 2007 1010
Change over time (no pun)Change over time (no pun)
Nothing you program should be set in stoneNothing you program should be set in stone
Sometimes your design changesSometimes your design changes
Need to go back and change your codeNeed to go back and change your code
Deprecated methods are those which have Deprecated methods are those which have been replaced…but left in place so your old been replaced…but left in place so your old stuff shouldn’t crash if you try to recompile stuff shouldn’t crash if you try to recompile with latest jdkwith latest jdk
Shlomo Hershkop 2007Shlomo Hershkop 2007 1111
Back to timeBack to time
System.currentTimeMillis()System.currentTimeMillis() Returns the current time on the systemReturns the current time on the system As a Date ObjectAs a Date Object
Shlomo Hershkop 2007Shlomo Hershkop 2007 1212
Ideas Ideas
Although would like to represent a Although would like to represent a point in time, usually time is point in time, usually time is associated with other measurementsassociated with other measurements
MonthMonth YearYear
Shlomo Hershkop 2007Shlomo Hershkop 2007 1313
The GregorianCalendar The GregorianCalendar ClassClass
The Date class doesn't measure The Date class doesn't measure months, weekdays, etc.months, weekdays, etc.
That's the job of a calendarThat's the job of a calendar A calendar assigns a name to a point A calendar assigns a name to a point
in timein time Many calendars in use:Many calendars in use:
GregorianGregorian Contemporary: Hebrew, Arabic, ChineseContemporary: Hebrew, Arabic, Chinese Historical: French Revolutionary, MayanHistorical: French Revolutionary, Mayan
Shlomo Hershkop 2007Shlomo Hershkop 2007 1414
RelationshipsRelationships
Shlomo Hershkop 2007Shlomo Hershkop 2007 1515
Next stepNext step
Lets design a new class to represent a Lets design a new class to represent a dayday
Today is TuesdayToday is TuesdayDay today = new Day();Day today = new Day();
Today.add(1);Today.add(1); //should give us Wednesday //should give us Wednesday
Shlomo Hershkop 2007Shlomo Hershkop 2007 1616
Goal of Day ClassGoal of Day Class
Answer questions such asAnswer questions such as
How many days are there between How many days are there between now and the end of the year?now and the end of the year?
What day is 100 days from now?What day is 100 days from now? How many days till my birthday (I’ve How many days till my birthday (I’ve
always wanted a _____________)always wanted a _____________)
Shlomo Hershkop 2007Shlomo Hershkop 2007 1717
Designing the classDesigning the class
Lets have a method Lets have a method daysFrom it computes number of days between two days:daysFrom it computes number of days between two days:
int n = today.daysFrom(birthday);int n = today.daysFrom(birthday);
addDays computes a day that is some days away from a addDays computes a day that is some days away from a given day:given day:
Day later = today.addDays(999);Day later = today.addDays(999);
Mathematical relationship:Mathematical relationship:
d.addDays(n).daysFrom(d) == nd.addDays(n).daysFrom(d) == nd1.addDays(d2.daysFrom(d1)) == d2d1.addDays(d2.daysFrom(d1)) == d2
Shlomo Hershkop 2007Shlomo Hershkop 2007 1818
Constructor Date(int year, int month, Constructor Date(int year, int month, int date)int date)
Will need the following methods:Will need the following methods: getYeargetYear getMonthgetMonth getDategetDate
Shlomo Hershkop 2007Shlomo Hershkop 2007 1919
ImplementationImplementation
Straightforward which member will need:Straightforward which member will need:
private int yearprivate int yearprivate int monthprivate int monthprivate int dateprivate int date
addDays/daysBetween tedious to implementaddDays/daysBetween tedious to implement April, June, September, November have 30 daysApril, June, September, November have 30 days February has 28 days, except in leap years it has 29 daysFebruary has 28 days, except in leap years it has 29 days All other months have 31 daysAll other months have 31 days Leap years are divisible by 4, except after 1582, years divisible Leap years are divisible by 4, except after 1582, years divisible
by 100 but not 400 are not leap yearsby 100 but not 400 are not leap years There is no year 0; year 1 is preceded by year -1There is no year 0; year 1 is preceded by year -1 In the switchover to the Gregorian calendar, ten days were In the switchover to the Gregorian calendar, ten days were
dropped: October 15, 1582 is preceded by October 4dropped: October 15, 1582 is preceded by October 4
Shlomo Hershkop 2007Shlomo Hershkop 2007 2020
Day CodeDay Code
public Day(int aYear, int aMonth, int aDate)public Day(int aYear, int aMonth, int aDate){{
year = aYear;year = aYear;month = aMonth;month = aMonth;date = aDate;date = aDate;
}}
private int year;private int year;private int month;private int month;private int date;private int date;
private static final int[] DAYS_PER_MONTH private static final int[] DAYS_PER_MONTH = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };= { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private static final int GREGORIAN_START_YEAR = 1582;private static final int GREGORIAN_START_YEAR = 1582;private static final int GREGORIAN_START_MONTH = 10;private static final int GREGORIAN_START_MONTH = 10;private static final int GREGORIAN_START_DAY = 15;private static final int GREGORIAN_START_DAY = 15;private static final int JULIAN_END_DAY = 4;private static final int JULIAN_END_DAY = 4;
private static final int JANUARY = 1;private static final int JANUARY = 1;private static final int FEBRUARY = 2;private static final int FEBRUARY = 2;private static final int DECEMBER = 12;private static final int DECEMBER = 12;
Shlomo Hershkop 2007Shlomo Hershkop 2007 2121
Day CodeDay Code
private Day nextDay()private Day nextDay()112: {112: {113: int y = year;113: int y = year;114: int m = month;114: int m = month;115: int d = date;115: int d = date;116: 116: 117: if (y == GREGORIAN_START_YEAR117: if (y == GREGORIAN_START_YEAR118: && m == GREGORIAN_START_MONTH118: && m == GREGORIAN_START_MONTH119: && d == JULIAN_END_DAY)119: && d == JULIAN_END_DAY)120: d = GREGORIAN_START_DAY;120: d = GREGORIAN_START_DAY;121: else if (d < daysPerMonth(y, m))121: else if (d < daysPerMonth(y, m))122: d++;122: d++;123: else123: else124: {124: {125: d = 1;125: d = 1;126: m++;126: m++;127: if (m > DECEMBER) 127: if (m > DECEMBER) 128: { 128: { 129: m = JANUARY; 129: m = JANUARY; 130: y++; 130: y++; 131: if (y == 0) y++;131: if (y == 0) y++;132: }132: }133: }133: }134: return new Day(y, m, d);134: return new Day(y, m, d);135: }135: }
Shlomo Hershkop 2007Shlomo Hershkop 2007 2222
private static int daysPerMonth(int y, int m)private static int daysPerMonth(int y, int m){{
int days = DAYS_PER_MONTH[m - 1];int days = DAYS_PER_MONTH[m - 1]; if (m == FEBRUARY && isLeapYear(y)) if (m == FEBRUARY && isLeapYear(y)) days++;days++; return days;return days;
}}
private static boolean isLeapYear(int y)private static boolean isLeapYear(int y){{if (y % 4 != 0) return false;if (y % 4 != 0) return false;if (y < GREGORIAN_START_YEAR) return true;if (y < GREGORIAN_START_YEAR) return true;return (y % 100 != 0) || (y % 400 == 0);return (y % 100 != 0) || (y % 400 == 0);}}
Shlomo Hershkop 2007Shlomo Hershkop 2007 2323
TesterTester
01: public class DayTester01: public class DayTester02: {02: {03: public static void main(String[] args)03: public static void main(String[] args)04: {04: {05: Day today = new Day(2001, 2, 3);05: Day today = new Day(2001, 2, 3);
//February 3, 2001//February 3, 200106: Day later = today.addDays(999);06: Day later = today.addDays(999);07: System.out.println(later.getYear() 07: System.out.println(later.getYear() 08: + "-" + later.getMonth() 08: + "-" + later.getMonth() 09: + "-" + later.getDate()); 09: + "-" + later.getDate()); 10: System.out.println(later.daysFrom(today));10: System.out.println(later.daysFrom(today));
// Prints 999// Prints 99911: }11: }12: }12: }
Shlomo Hershkop 2007Shlomo Hershkop 2007 2424
Notice Notice
Private helper methodsPrivate helper methods
Notice all the work to increment a Notice all the work to increment a dayday
Shlomo Hershkop 2007Shlomo Hershkop 2007 2525
Another ideaAnother idea
This is for illustration, don’t need to codeThis is for illustration, don’t need to code
For greater efficiency, we can use Julian For greater efficiency, we can use Julian day numberday number
Used in astronomyUsed in astronomy Number of days since Jan. 1, 4713 BCENumber of days since Jan. 1, 4713 BCE May 23, 1968 = Julian Day 2,440,000May 23, 1968 = Julian Day 2,440,000 Greatly simplifies date arithmeticGreatly simplifies date arithmetic
Shlomo Hershkop 2007Shlomo Hershkop 2007 2626
CodeCode
public Day(int aYear, int aMonth, int aDate)public Day(int aYear, int aMonth, int aDate)
{{
//notice we are calling a private//notice we are calling a private
//helper function//helper function
julian = toJulian(aYear, aMonth, aDate);julian = toJulian(aYear, aMonth, aDate);
}}
//that’s all we need//that’s all we need
private int julian;private int julian;
Shlomo Hershkop 2007Shlomo Hershkop 2007 2727
Helper functionHelper function
private static int toJulian(int year, int month, int date)private static int toJulian(int year, int month, int date){ {
int jy = year;int jy = year;if (year < 0) jy++;if (year < 0) jy++;int jm = month;int jm = month;if (month > 2) jm++;if (month > 2) jm++;else{ else{
jy--;jy--;jm += 13;jm += 13;
}}int jul = (int) (java.lang.Math.floor(365.25 * jy) int jul = (int) (java.lang.Math.floor(365.25 * jy) + java.lang.Math.floor(30.6001 * jm) + date + 1720995.0);+ java.lang.Math.floor(30.6001 * jm) + date + 1720995.0);int IGREG = 15 + 31 * (10 + 12 * 1582);int IGREG = 15 + 31 * (10 + 12 * 1582);
// Gregorian Calendar adopted Oct. 15, 1582// Gregorian Calendar adopted Oct. 15, 1582if (date + 31 * (month + 12 * year) >= IGREG)if (date + 31 * (month + 12 * year) >= IGREG)// Change over to Gregorian calendar// Change over to Gregorian calendar{ { int ja = (int) (0.01 * jy);int ja = (int) (0.01 * jy);jul += 2 - ja + (int) (0.25 * ja);jul += 2 - ja + (int) (0.25 * ja);}}return jul;return jul;
}}
Shlomo Hershkop 2007Shlomo Hershkop 2007 2828
Any other ideas?Any other ideas?
So you see that using the class doesn’t So you see that using the class doesn’t change even though we totally changed change even though we totally changed how the inside workshow the inside works Called encapsulationCalled encapsulation
So its easy to move up or down the So its easy to move up or down the calendarcalendar Add subtractAdd subtract
Where would it cost us ??Where would it cost us ??
Shlomo Hershkop 2007Shlomo Hershkop 2007 2929
Switch gearsSwitch gears
Lets talk about how to use filesLets talk about how to use files
Your program starts in main, computes, Your program starts in main, computes, then maybe prints out something before then maybe prints out something before closing upclosing up
Would be great if can save results Would be great if can save results somewheresomewhere Hey lets use files Hey lets use files
Shlomo Hershkop 2007Shlomo Hershkop 2007 3030
File manipulationsFile manipulations
Working with filesWorking with files
Reading filesReading files
Writing filesWriting files
Shlomo Hershkop 2007Shlomo Hershkop 2007 3131
Please notePlease note
One of the great things about file One of the great things about file manipulation on java is that it is the manipulation on java is that it is the same on same on WindowsWindows LinuxLinux MacMac
If done rightIf done right
Shlomo Hershkop 2007Shlomo Hershkop 2007 3232
FileFile
Basic object is called FileBasic object is called File
File data = new File(“test.txt”);File data = new File(“test.txt”);
It will look in the same directory the java It will look in the same directory the java file is sitting in for the test filefile is sitting in for the test file
Calling: data.getAbsolutePath()Calling: data.getAbsolutePath() Will print out the local version of the full path Will print out the local version of the full path
to the fileto the file
Shlomo Hershkop 2007Shlomo Hershkop 2007 3333
Directories Directories
If your File object is a directoryIf your File object is a directory The list method returns an array of The list method returns an array of
String file names, String file names, listFiles returns an array of File listFiles returns an array of File
objectsobjects
Shlomo Hershkop 2007Shlomo Hershkop 2007 3434
limitationslimitations
The File object has a limited number The File object has a limited number of useful methodsof useful methods
None which can actually write None which can actually write something to itsomething to it
Need to use higher level class to Need to use higher level class to work with file contentswork with file contents
Shlomo Hershkop 2007Shlomo Hershkop 2007 3535
Dealing with textDealing with text
When dealing with text output/input When dealing with text output/input can usecan use
PrintWriter to write to a filePrintWriter to write to a file
Shlomo Hershkop 2007Shlomo Hershkop 2007 3636
codecode
PrintWriter pw = new PrintWriter(new PrintWriter pw = new PrintWriter(new FileWriter(new File("Test.txt")));FileWriter(new File("Test.txt")));
What is FileWriter ?What is FileWriter ?
Lets pull up the APILets pull up the API
Shlomo Hershkop 2007Shlomo Hershkop 2007 3737
Helper class to help make sure things Helper class to help make sure things are written efficientlyare written efficiently
Don’t forget to close the file handle Don’t forget to close the file handle when donewhen done
And flush if using a buffered handleAnd flush if using a buffered handle
Shlomo Hershkop 2007Shlomo Hershkop 2007 3838
Ok lets write some codeOk lets write some code
Main programMain program
Will write a 3 line poem (yes you need to Will write a 3 line poem (yes you need to write one now) to a test.txt filewrite one now) to a test.txt file
Notice how your have to add try catch to Notice how your have to add try catch to handle certain declared exceptions ??handle certain declared exceptions ??
Shlomo Hershkop 2007Shlomo Hershkop 2007 3939
Run codeRun code
Confirm that the file has been Confirm that the file has been createdcreated
Now write another class to read the Now write another class to read the filefile
Shlomo Hershkop 2007Shlomo Hershkop 2007 4040
How would you adopt the reader to How would you adopt the reader to find something in the file ??find something in the file ??
Shlomo Hershkop 2007Shlomo Hershkop 2007 4141
For each line readFor each line read
Look for somethingLook for something
See String API for helper methodsSee String API for helper methods
Now write the code Now write the code
Shlomo Hershkop 2007Shlomo Hershkop 2007 4242
Next upNext up
InterfacesInterfaces InheritanceInheritance Abstract ClassesAbstract Classes PolymorphismPolymorphism GenericsGenerics
Shlomo Hershkop 2007Shlomo Hershkop 2007 4343
Two dimensionsTwo dimensions
You can also initialize the inner array as a You can also initialize the inner array as a separate call.separate call.
Doesn’t have to be congruous memory Doesn’t have to be congruous memory locationslocations
int [][]example = new int[5][];int [][]example = new int[5][];
for (int i=0;i<5;i++){for (int i=0;i<5;i++){
example[i] = new int[i+1];example[i] = new int[i+1];
}}
Shlomo Hershkop 2007Shlomo Hershkop 2007 4444
InterfaceInterface
An interface is a special class that An interface is a special class that defines the behavior of other classesdefines the behavior of other classes
Example Example How many mp3 players are on the How many mp3 players are on the
market ?market ?
Shlomo Hershkop 2007Shlomo Hershkop 2007 4545
Mp3 playersMp3 players
No matter what type of mp3 player you No matter what type of mp3 player you buy you expect certain behaviorbuy you expect certain behavior
PlayPlay Forward(next song)Forward(next song) Rewind(last song)Rewind(last song) RandomRandom
Think of your ownThink of your own
Shlomo Hershkop 2007Shlomo Hershkop 2007 4646
If I want to program a bunch of mp3 If I want to program a bunch of mp3 players and want to force all of them players and want to force all of them to have some minimum behavior I to have some minimum behavior I would encode that as an interfacewould encode that as an interface
Here is an example:Here is an example:
Shlomo Hershkop 2007Shlomo Hershkop 2007 4747
codecode
public interface mp3player {public interface mp3player {
public boolean play();public boolean play();
public boolean rewind();public boolean rewind();
public boolean forward();public boolean forward();
public int getSongCount();public int getSongCount();
public boolean deleteAll();public boolean deleteAll();
}}
Shlomo Hershkop 2007Shlomo Hershkop 2007 4848
analysisanalysis
Basically am defining ideasBasically am defining ideas
Would add comments to each what Would add comments to each what they are supposed to be doing they are supposed to be doing (expected behavior(expected behavior
Then any class which wants to be Then any class which wants to be nice, would agree to behave this waynice, would agree to behave this way
Shlomo Hershkop 2007Shlomo Hershkop 2007 4949
Code: IpodMP3Code: IpodMP3
Say we want to create a really cool Say we want to create a really cool mapple ipod playermapple ipod player
Want to stick to the mp3 behaviorWant to stick to the mp3 behaviorpublic class Ipodmp3 implements mp3player public class Ipodmp3 implements mp3player { ..{ ..
This means that we need to define This means that we need to define those methods for this specific classthose methods for this specific class
Shlomo Hershkop 2007Shlomo Hershkop 2007 5050
Note Note
Can implement as many interfaces as you likeCan implement as many interfaces as you like Will notice them in the api when you look at Will notice them in the api when you look at
the standard librariesthe standard libraries Compiler will check and complain if you don’t Compiler will check and complain if you don’t
implement all the methods you are promising implement all the methods you are promising in the interface you implimentin the interface you impliment
Nothing actually checks that you are doing the Nothing actually checks that you are doing the correct thing….that is up to the programmercorrect thing….that is up to the programmer
Shlomo Hershkop 2007Shlomo Hershkop 2007 5151
GASP!GASP!
Question: so what does : Question: so what does : Ipodmp3 player1 = new Ipodmp3 ();Ipodmp3 player1 = new Ipodmp3 ();player1.play()player1.play()actually do ??actually do ??
Answer: Maybe erase your hard Answer: Maybe erase your hard drive…look at the source code drive…look at the source code
Shlomo Hershkop 2007Shlomo Hershkop 2007 5252
IteratorsIterators
Many of the classes in Java represent Many of the classes in Java represent a collection of itemsa collection of items
Some have orderSome have order Some don’t have orderSome don’t have order
All the students in one roomAll the students in one room Alphabetical listAlphabetical list Bag of names (raffle)Bag of names (raffle)
Shlomo Hershkop 2007Shlomo Hershkop 2007 5353
Two typesTwo types
Here is a general Iterator ideaHere is a general Iterator idea
Get the iterator object from the classGet the iterator object from the class
Can ask the iterator object if it has any Can ask the iterator object if it has any more stuff more stuff
Get the next thingGet the next thing
Shlomo Hershkop 2007Shlomo Hershkop 2007 5454
Inheritance Inheritance
You have a really useful classYou have a really useful class Want to specialize it in more than one Want to specialize it in more than one
wayway
Can either copy paste a bunch of time Can either copy paste a bunch of time and tweak each copyand tweak each copy
Problem if we find a bug, will need to Problem if we find a bug, will need to run to all copies and fix everythingrun to all copies and fix everything
Shlomo Hershkop 2007Shlomo Hershkop 2007 5555
Easier way:Easier way:
Look at all the classes that are related, Look at all the classes that are related, what ideas do they all sharewhat ideas do they all share
Example: what is common between all Example: what is common between all kinds of carskinds of cars
Make that idea the base class, and each Make that idea the base class, and each specialization a sub classspecialization a sub class
Known as inheritance!Known as inheritance!
Shlomo Hershkop 2007Shlomo Hershkop 2007 5656
Inheritance Inheritance
Use the ‘extends’ keywordUse the ‘extends’ keyword Allows you to reuse objectsAllows you to reuse objects
Some issues:Some issues: When do you extend?When do you extend? When do you implement an interface?When do you implement an interface?
Shlomo Hershkop 2007Shlomo Hershkop 2007 5757
ExampleExample
Geneal idea of an AnimalGeneal idea of an Animal Can code it as class AnimalCan code it as class Animal Then have specific codeThen have specific code
class Horse extends Animalclass Horse extends Animal class Whale extends Animalclass Whale extends Animal
What ever methods are the same in both What ever methods are the same in both would be coded in the Animal class, would be coded in the Animal class, specific methods (numberLegs() would be specific methods (numberLegs() would be defined in the specific subclass)defined in the specific subclass)
Shlomo Hershkop 2007Shlomo Hershkop 2007 5858
Super constructorsSuper constructors
When refering to parent class (Animal)When refering to parent class (Animal) Use super keyword in subclass constructor:Use super keyword in subclass constructor: public Horse(String aName)public Horse(String aName) {{ super(aName); // calls superclass constructorsuper(aName); // calls superclass constructor //rest of your stuff here//rest of your stuff here }} Call to super must be first statement in subclass Call to super must be first statement in subclass
constructorconstructor If subclass constructor doesn't call super, If subclass constructor doesn't call super,
superclass must have constructor without superclass must have constructor without parametersparameters
Shlomo Hershkop 2007Shlomo Hershkop 2007 5959
Polymorphism Polymorphism
This is just fancy word that tells you java This is just fancy word that tells you java will figure out the following code:will figure out the following code:
Animal A = new Horse(“tom”);Animal A = new Horse(“tom”);
So although A is really a horse, it can be So although A is really a horse, it can be refered to by parent handle.refered to by parent handle.
This would be illigal:This would be illigal: Horse A = new Whale();Horse A = new Whale(); Why ?Why ?
Shlomo Hershkop 2007Shlomo Hershkop 2007 6060
NextNext
Imagine you have a class which has variable Imagine you have a class which has variable members of a specific typemembers of a specific type
Example:Example:
Have a list of numbers, say a list of zip codes Have a list of numbers, say a list of zip codes which you have sent packages in the last X which you have sent packages in the last X monthsmonths
What if you want to change zip codes to Strings What if you want to change zip codes to Strings because you are now sending packages to because you are now sending packages to canadacanada
Shlomo Hershkop 2007Shlomo Hershkop 2007 6161
2 solutions2 solutions
Copy paste code and replace all ints Copy paste code and replace all ints with Stringswith Strings
Debug like crazyDebug like crazy
…….or use Generics.or use Generics
Shlomo Hershkop 2007Shlomo Hershkop 2007 6262
Basic ideaBasic idea
Tell java you are dealing with some Tell java you are dealing with some type without know what it istype without know what it is
Can set some rules on itCan set some rules on it
When you create an instance of the When you create an instance of the object you will tell java what you wantobject you will tell java what you want
Shlomo Hershkop 2007Shlomo Hershkop 2007 6363
CodeCode
public class shoppingList<T> {public class shoppingList<T> {
private ArrayList<T> theList;private ArrayList<T> theList;
shoppingList(){shoppingList(){theList = new ArrayList<T>();theList = new ArrayList<T>();
}}
public void addItem(T item){public void addItem(T item){theList.add(item);theList.add(item);
}}
public int getNumberOnList(){public int getNumberOnList(){return theList.size();return theList.size();
}}
public T getItemAt(int location){public T getItemAt(int location){return theList.get(location);return theList.get(location);
}}}}
Shlomo Hershkop 2007Shlomo Hershkop 2007 6464
Code 1Code 1
//once you get previous screen running at the following //once you get previous screen running at the following methodmethod
public void showType() { public void showType() { System.out.println("Type of T is " + System.out.println("Type of T is " + ob.getClass().getName()); ob.getClass().getName()); } }
Shlomo Hershkop 2007Shlomo Hershkop 2007 6565
Usage Usage
shoppingList<Integer> e1; shoppingList<Integer> e1;
e1 = new shoppingList<Integer>; e1 = new shoppingList<Integer>; e1.add(15); e1.add(15);
int v = e1.getItemAt(0); int v = e1.getItemAt(0);
Write a main to test the idea of genericsWrite a main to test the idea of generics
Shlomo Hershkop 2007Shlomo Hershkop 2007 6666
Example2Example2
class Example2<T, V> { class Example2<T, V> { T ob1; T ob1; V ob2; V ob2;
Example2(T o1, V o2) { Example2(T o1, V o2) { ob1 = o1; ob1 = o1; ob2 = o2; ob2 = o2; } }
T getob1() { T getob1() { return ob1; return ob1; } }
V getob2() { V getob2() { return ob2; return ob2; } } }}
Shlomo Hershkop 2007Shlomo Hershkop 2007 6767
Example 3Example 3
class Example3<Q extends Number> { class Example3<Q extends Number> {
Q[] nums; // array of Number or subclass Q[] nums; // array of Number or subclass
Stats(Q[] o) { Stats(Q[] o) { nums = o; nums = o; } }
double sum() { double sum() { double sum = 0.0; double sum = 0.0; for(int i=0; i < nums.length; i++) for(int i=0; i < nums.length; i++) sum += nums[i].doubleValue(); sum += nums[i].doubleValue(); return sum; return sum; } } } }
Shlomo Hershkop 2007Shlomo Hershkop 2007 6868
Usage Usage
Double dnums[] ={ 1.1, 2.2, 3.3, 4.4, 5.5 }; Double dnums[] ={ 1.1, 2.2, 3.3, 4.4, 5.5 };
Example3<Double> dob = new Example3<Double> dob = new Example3<Double>(dnums); Example3<Double>(dnums);
double w = dob.sum(); double w = dob.sum();
System.out.println("dob sum is " + w); System.out.println("dob sum is " + w);
Shlomo Hershkop 2007Shlomo Hershkop 2007 6969
Example4Example4class TwoD { class TwoD { int x, y; int x, y; TwoD(int a, int b) { TwoD(int a, int b) { x = a; x = a; y = b; y = b; } } } }
class ThreeD extends TwoD { class ThreeD extends TwoD { int z; int z; ThreeD(int a, int b, int c) { ThreeD(int a, int b, int c) { super(a, b); super(a, b); z = c; z = c; } } } }
class FourD extends ThreeD { class FourD extends ThreeD { int t; int t; FourD(int a, int b, int c, int d) { FourD(int a, int b, int c, int d) { super(a, b, c); super(a, b, c); t = d; t = d; } } } }
Shlomo Hershkop 2007Shlomo Hershkop 2007 7070
class Coords<T extends TwoD> { class Coords<T extends TwoD> {
T[] coords; T[] coords;
Coords(T[] o) { coords = o; } Coords(T[] o) { coords = o; }
} }
Shlomo Hershkop 2007Shlomo Hershkop 2007 7171
static void showXY(Coords<?> c) { static void showXY(Coords<?> c) { System.out.println("X Y Coordinates:"); System.out.println("X Y Coordinates:"); for(int i=0; i < c.coords.length; i++) for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " System.out.println(c.coords[i].x + " " + +
c.coords[i].y); c.coords[i].y); System.out.println(); System.out.println(); } }
Shlomo Hershkop 2007Shlomo Hershkop 2007 7272
static void showXYZ(Coords<? extends ThreeD> c) { static void showXYZ(Coords<? extends ThreeD> c) { System.out.println("X Y Z Coordinates:"); System.out.println("X Y Z Coordinates:"); for(int i=0; i < c.coords.length; i++) for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " + System.out.println(c.coords[i].x + " " + c.coords[i].y + " " + c.coords[i].y + " " + c.coords[i].z); c.coords[i].z); System.out.println(); System.out.println(); } }
Shlomo Hershkop 2007Shlomo Hershkop 2007 7373
static void showAll(Coords<? extends FourD> c) { static void showAll(Coords<? extends FourD> c) { System.out.println("X Y Z T Coordinates:"); System.out.println("X Y Z T Coordinates:"); for(int i=0; i < c.coords.length; i++) for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " + System.out.println(c.coords[i].x + " " + c.coords[i].y + " " + c.coords[i].y + " " + c.coords[i].z + " " + c.coords[i].z + " " + c.coords[i].t); c.coords[i].t); System.out.println(); System.out.println(); } }
Shlomo Hershkop 2007Shlomo Hershkop 2007 7474
Using in methodsUsing in methods
Just learn how to read the following:Just learn how to read the following:
static <T, V extends T> boolean isIn(T x, V[] y) { static <T, V extends T> boolean isIn(T x, V[] y) {
for(int i=0; i < y.length; i++) for(int i=0; i < y.length; i++) {{
if(x.equals(y[i])) return true; if(x.equals(y[i])) return true; }}
return false; return false;
} }
Shlomo Hershkop 2007Shlomo Hershkop 2007 7575
Hope you had fun learning this!Hope you had fun learning this!