Upload
others
View
17
Download
0
Embed Size (px)
Citation preview
CS360ProgrammingLanguagesIntroductiontoJava
Theplan
• Racketwillreturn!– FinalprojectwillbewritingaRacketinterpreterinJava.
• LecturewillnotdiscusseverysinglefeatureofJava.– Youmayneedtodosomediggingonyourown.– Lotsofhelponline(Googleisyourfriend).
JavaResources
• Javatutorial– http://docs.oracle.com/javase/tutorial/java
• Javadocumentation– http://docs.oracle.com/javase/8/docs/api
• Andifyou'reconfusedaboutanything,Googlewillfindit.– There'ssomuchJavastuffonthewebbecausemostundergraduate
curriculumsnowteachJavaastheirfirstorsecondlanguage.
Logistics
• WewilluseJavaversion8.
– ThoughprobablymostofthecodeIwillshowiscompatiblebacktoJava6and7.
– Java9wasjustreleasedaboutsixweeksago.
• ManypowerfulIDEsoutthere.
– IwillbeusinganIDEcalledNetBeans,whichisfree.
– Installationinstructionswillbeontheclasswebpage.
NextAssignments
• Overlappingtimeframesforthelastassignments.• Project4– outtoday,stillinRacket
– Outtoday– DueTueNov14
• Project5– Javawarmupassignment– OutThuNov9– DueTueNov21[daybeforeThanksgivingbreak].
• Project6– Javaproject involvingthreadsandconcurrency– OutTueNov14– DueTueNov28
• Project7– RacketinterpreterinJava.– OutTueNov28– Dueduringfinalexams(probablyTueDec12).
HistoryofJava
HistoryofJava
• Javawasfirstusedinthe15th century,inYemen,andquicklyspreadtoEgyptandNorthAfrica.
TheRealHistoryofJava
TheRealHistoryofJava
• Javaismillionsofyearsoldand135millionpeopleseeJavaeveryday.
TheReal,RealHistoryofJava
• TheJavaprojectwasinitiatedatSunMicrosystemsin1991.– Supposedlynamedafterthelargequantitiesofcoffeethelanguage
designersdrank.
• Originallywasdesignedtobeembeddedinconsumerelectronicdevices,likecableTVset-topboxes,butitwastooadvancedforthecabletelevisionindustryatthetime.
• Languageevolvedintoageneral-purposeprogramminglanguage.
TheReal,RealHistoryofJava
• JavawasdesignedtouseasyntaxsimilartoCandC++.– Lotswillbefamiliar.
• Javais(almostcompletely)objectoriented.– Alldatatypesareclasses,exceptfortheprimitiveslikeint,long,float,
double,char,boolean.– Allcodeiswritteninsidesomeclass.
• Allfunctionsaremethods(nofree-floatingfunctions).– Singleinheritanceonly(C++allowsmultiple).
• Staticallytyped(likeC++,).
• Hasgenerics (similartoC++templates).
TheReal,RealHistoryofJava
• SamebasicprogrammingpropertiesasC++.– Mustdeclarevariablesbeforeuse,saywhattypetheyare.– If/else,for,while,do-while,switchworkjustlikeC++.
• Nopointers!– Javausesasimilarideacalledreferences,whichare"safer"than
pointers.
• Allobjectsstoredontheheap(using"new").
• Garbagecollection– Noexplicitallocation/deallocationofmemory.(nomalloc/free)
Definingaclass
• TakealookattheRationalclass.
• CreateprimitivevariablesjustlikeinC++:– int x=4;– floatf=3.02;– boolean b=true;//notelowercase
• Stringsareobjects,butJavaletsyoucreatethemlikeaprimitive:– Strings="awonderfulstring";
• Allotherobjectsarecreatedusingnew:– ClassName var =newClassName(args);– Constructorautomaticallychosenbasedondatatypesofarguments.
• Variablesdeclaredinaclassarecalledfields or instancevariables.(likeC++)
• Instancesofaclasshaveonecopyoftheirfieldsorinstancevariables.
• Contrastwithclassvariablesor staticvariables:onecopyofthevariablethatissharedamongallinstancesoftheclass.– Declaredwithstatic keyword.
• Functionsdeclaredinaclassknownasmethods.
• Instancemethodscanaccessinstancevariables,andarecalledusingC++-likesyntax:– ClassName var = new ClassName();– var.name_of_method(arg1, arg2, ...);
• Classmethodsorstaticmethodsarecalledonthenameoftheclassitself,notaninstanceoftheclass.– ClassName.name_of_instance_method(args);– example: Integer.toString(int), Math.pow(x, y)
Class/Method/VariableVisibility
• public:availableeverywhere• protected:onlyavailablewithintheclassandsubclasses• private:onlyavailablewithintheclass
• SimilartoC++:– Haveanumberofprivateinstancevariablesthatmaintainthe"state"of
theclass.– Haveanumberofpublicmethodsthatarepartoftheclass'sinterface.– Alsocommontohaveprivate"helper"methods.
• JavatraditionallyusesCamelCase ratherthanseparating_with_underscores.• variablesandmethodsstartwithalowercaseletter.• Classnamesstartwithanuppercaseletter.• "this"worksjustlikeinC++.• Allobjectsbydefaultinheritfromthe"Object"baseclass.
Gettingaprogramstarted
• Eachclassmustgoinitsownfile,whichmustbenamedClassName.java.• Anyclasscanhaveapublicstaticmain()method,whichiswherethe
executionstarts.
Packages
• Java'sstandardlibrary(allthefunctionsthatthelanguagecomeswith)areorganizedintopackages– Ahierarchicalorganizationsystem.
• InJavayou"import"classesfrompackages,whereasinC++you"#include"files.
Collections
• Builtinclassesfor– Lists(ArrayList,LinkedList,…)– Sets(HashSet,…)– Maps(whatJavacallshashtables)(HashMap)
• Alloftheseareparameterizedwithgenerics.– List<Integer>intlist =newList<Integer>();– intlist.add(17);– System.out.println(intlist);//prints[17]
Today'splan
• IntroduceOOPconceptsfromthegroundupusingJava.– Rehashof142-ishthingsbutatadeeperlevelofunderstanding.
• Talkaboutwhy/whenyoushouldorshouldn'tdocertainOOPthings.
• LotsofthingswillbefamiliarfromC++.
• Somethingswillbedifferent.
public class Point{private int x, y;public Point(int x, int y) { this.x = x; this.y = y;
}public int getX() { return x; }public int getY() { return y; }public void setX(int x) { this.x = x; }public void setY(int y) { this.y = y; }public double distFromOrigin() {return Math.sqrt(x * x + y * y)
}}
Subclassing
• Aclassdefinitionhasasuperclass(Object ifnotspecified)
• Thesuperclassaffectstheclassdefinition:– Classinherits allfielddeclarationsfromsuperclass– Classinherits allprivatemethoddefinitionsfromsuperclass
• Codewithinthesubclasscannotdirectlyaccessanyprivatefieldsormethods.
– Butclasscanoverridemethoddefinitionsasdesired
class ColorPoint extends Point { … }
public class ColorPoint extends Point{private Color color;public ColorPoint(int x, int y, Color c) {super(x, y); // call the superclass constructorthis.color = c;
}public Color getColor() { return color; }public void setColor(Color c) { this.color = c; }
}
Anobjecthasaclass
• Usinginstanceof canindicate bad OO style.– If you're using it to do something different for different objects types,
you probably meant to write a method and have subclasses override the method.
• instanceof is an example of using reflection– Reflection is the ability for a computer program to be able to
examine its structure and behavior at run-time.
Point p = new Point(0, 0);ColorPoint cp = new ColorPoint(0, 0, Color.red)
/* instanceof is a keyword that returns trueif a variable is an instance of a class. */
p instanceof Point // truecp instanceof ColorPoint // truecp instanceof Point // true
Whysubclass?
• InsteadofcreatingColorPoint,couldaddmethodstoPoint– Thatcouldmessupotherusersandsubclassers ofPoint
public class Point {private int x, y;private Color color; …
public Point(x, y) { // what does color get set to?
}}
Whysubclass?
• Insteadofsubclassing Point,couldcopy/pastethemethods– Meansthesamethingif youdon'tuseinstanceof,butofcoursecode
reuseisnice
public class ColorPoint {private int x, y;private Color color; …
}
ColorPoint cp = new ColorPoint( whatevs )if (cp instanceof Point) {// do pointy things
}
Whysubclass?
• Insteadofsubclassing Point,coulduseaPoint instancevariableinsideofColorPoint.– DefinemethodstosendsamemessagetothePoint– Thisiscalledobjectcomposition;expressesa"hasa"relationship.– ButforColorPoint,subclassing makessense:lessworkandcanuseaColorPoint wherevercodeexpectsaPoint
public class ColorPoint {private Point point;private Color color;public setX(int x) { point.setX(x); }…
}
Is-avs has-a
• OObeginnerstendtooveruseinheritance(theis-arelationship).
• OOinheritanceisnotoriouslytrickytogetrightsometimes(e.g.,writingmethodsthattestforequality)– boolean equals(Pointa,Pointb)– Whatifa&bcanbePointsorColorPoints?
• Manyreal-worldrelationshipscanbeexpressedusingis-aorhas-a,evenifthemostnaturalwayseemstobeis-a.– ColorPoint couldbewrittenusingobjectcomposition.
Circleandellipseproblem
• WhatshouldtherelationshipbebetweenaCircleclassandanEllipseclass?
Circleandellipseproblem
• Circlesarespecifictypesofellipses,soaCircleis-a Ellipse.
public class Ellipse {
private int radiusX, int radiusY;
public void setRadiusX(int rx) { radiusX = rx; }
public void setRadiusX(int rx) { radiusY = ry; }
public int getRadiusX() { return radiusX; }
public int getRadiusY() { return radiusY; }
}
public class Circle extends Ellipse {
…
}
Circleandellipseproblem
• Circlesarespecifictypesofellipses,soaCircleis-a Ellipse.
• ButnowCirclehasasetRadiusX()method.
• Furthermore,whatwouldthatmethod'simplementationlooklike?
Circleandellipseproblem
• Differentsolution:makeEllipseasubclassofCircle.– "AnEllipseisaCirclewithanextraradiusfield."
public class Circle {
private int radius;
public void setRadius(int r) { radius = r; }
public int getRadius() { return radius; }
}
public class Ellipse extends Circle {
private int radiusY;
// assume existing radius is for X dimension.
}
Circleandellipseproblem
• Differentsolution:makeEllipseasubclassofCircle.– "AnEllipseisaCirclewithanextraradiusfield."
• Justasmanyproblemshere:
• WhatdoesitmeanwhenanEllipsecallsCircle'ssetRadius orgetRadiusmethod(whichradius?)
Onesolution:Immutability
• LetCircleinheritfromEllipseandeliminatemutator methods.
public class Ellipse {
private int radiusX, int radiusY;
public int getRadiusX() { return radiusX; }
public int getRadiusY() { return radiusY; }
}
public class Circle extends Ellipse { … }
• Circle still has two radius accessor methods.• As long as Circle's constructor forces radiusX = radiusY, there's no
way to violate that constraint later.
Othersolutions
• Let Circle and Ellipse inherit from some common superclass (rather than one from the other).
• Let setRadiusX() return success or failure.
• Drop inheritance entirely.
• Drop Circle; let users (manually) handle circles as instances of Ellipse.
Whatinheritancereallyisfor
• Inheritancegetsyouintotroublewhenitseemsliketherelationshipis"is-a,"butitactuallyis"is-a-restricted-version-of."– CircleandEllipse– PersonandToddler
• CertainlyaToddlerisaPerson.• ButwhatifaPersonhasamethodcalledwalk(int distance).• Toddlerscan'twalk!
• Inheritanceshouldbeusedtoaddextradetailtoasuperclass(e.g.,aMonkeyisanAnimal),nottorestrictfunctionality.– ColorPoint is(probably)finetoinheritfromPoint
Trythisoneout
• IwanttodeclareaclassThreeDPoint.
• ShouldthisinheritfromPoint?– Whataretheprosandcons?
Somethingdifferent:Methodoverriding
• InOOP,asubclassmayoverrideamethodfromasuperclass.• Justre-definethemethodinthesubclass.
InC++,whatdoesthisdo?class Base {
public: int f() { return 1; } };
class Derived: public Base {
public: int f() { return 2; } };
int main() {
Base b;
Derived d;
cout << b.f() << endl;
cout << d.f() << endl;
b = d;
cout << b.f() << endl;
Base *b2 = &d;
cout << b2->f() << endl;
}
Base *b2 = &d;cout << b2->f() << endl;
• Withapointertoanobject,acalltoamethodofthatobjectcallstheversionofthemethodspecifiedbythetypeofthepointer,notthetypeoftheobjectbeingpointedto.
• CanbechangedwiththeC++keywordvirtual.
• Withapointertoanobject,acalltoavirtualmethodofthatobjectcallstheversionofthemethodspecifiedbythetypeoftheobjectbeingpointedto.
InC++,whatdoesthisdo?class Base {
public: virtual int f() { return 1; } };
class Derived: public Base {
public: int f() { return 2; } };
int main() {
Base b;
Derived d;
cout << b.f() << endl;
cout << d.f() << endl;
b = d;
cout << b.f() << endl;
Base *b2 = &d;
cout << b2->f() << endl;
}
• Thekeyideahereiscalleddynamicdispatch:– Selectingwhichimplementationofapolymorphicoperationtocallat
run-time,ratherthancompile-time.• Thisistheoppositeofwhatwe'velearnedaboutlexical(static)scope:
– Inlexicalscope,wealwaysknowatcompile-timewhatvariableswillbereferredtoandwhatfunctionswillbecalled.
• WithOOP,itispossibleforavariabletorefertoanobjectwhosetypeisuncertainatcompiletime.
Base b;
Derived d;
Base *b2 = nullptr;
if (rand() > 0.5))
b2 = &b;
else
b2 = &d;
b2->f();
Javavirtualmethods
• InJava,allmethodsarevirtual.– Thisbehaviorcannotbechanged.– Ifasubclassneedstocallasuperclass'sversionofanoverriddenmethod
fromasubclass,thereisthesuper keyword:
public class Base {
public int f() { return 1; } }
public class Derived extends Base {
public int f() { return 2 + super.f(); } }
Javavirtualmethods
public class ThreeDPoint extends Point{private int z;
// override distFromOrigin in Pointpublic double distFromOrigin() {return Math.sqrt(getX()*getX() + getY()*getY() + z*z;
}}
JavaI/O
• Mainwayofoutputtingtothescreen:
• System.out.println(x);– takesoneargumentofanytype– ifxisanobject,itstoString()methodwillbeautomaticallycalledto
convertittoaString.– alsoSystem.err.println(x);
– System.out isanOutputStream object(similartocout inC++)
JavaI/O
• Thereareabout50bazillionwaystodoinputinJava.• Easiestway:
– import java.util.*;– Scanner scanner = new Scanner(System.in)
• System.in isanInputStream object(similartocin inC++)– Nowcallanyofthefollowing:– scanner.nextInt() [ornextLong(),nextFloat(),etc]
• allofthesestopatthefirstwhitespacefound– scanner.nextLine()
• readsawholeline,returnsaString
Trythis
• Makeaprogramthatreadsinintegersfromthekeyboarduntilyouenter-1.
Collections
• Javahasmanycollectionclasses.– ArrayList,HashSet,HashMap mostcommon.– Veryfewcaseswhereyouneed"real"arrays;usingArrayList ismuch
morecommon.
• SyntaxissimilartoC++templates– e.g.,C++'svector,set,andmap
• Gotcha:OnlyobjectscanbestoredinJava'scollectionclasses.– Noints,floats,booleans,doubles,etc inArrayLists!– Javahas"wrapper"classesInteger,Float,Boolean,Doublethatyouuse
instead,andJavadoestheconversionforyou.
ArrayList (exampleforints)
• Creation– List<Integer> list = new ArrayList<Integer>();
• Putstuffin– list.add(x); // adds x to end by default– list.add(i, x); // inserts x at list[i]– list.set(i, x); // changes list[i] to x
• Getstuffout– list.get(i); // returns list[i]
• Other stuff– list.size(), list.contains(x), list.indexOf(x), list.remove(i),
Enhancedforloop
for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));
}
for (int x : list) {System.out.println(x);
}
Trythis
• Makeaprogramthatreadsinintegersfromthekeyboarduntilyouenter-1.• Addalltheintegers(asthey'reentered)toanArrayList.• Printoutalltheintegers.Trythistwoways:
– System.out.println(list);– Withtheenhancedforloop.
Trythis
• Makeaprogramthatreadsinintegersfromthekeyboarduntilyouenter-1.• Addastaticmethodfib(n)thatcomputesthen'th Fibonaccinumber.Write
thisthestandard(slow,recursive)way.• PrintouttheFibonaccivalueofeachnumberasthey'reentered.
– WhatisthemaxFibonacci#youcancomputebeforeyougetanerror?
HashMaps
• Java'shasafewhashtable classes.• MostcommonisHashMap.
• TheJavalanguagewasconstructedwithhashtables inmind.• TheObjectclasshasahashCode()method.
– Becauseallobjectsinherit(directlyorindirectly)fromObject,allclasseshaveahashCode()method!
• Ifyouevermakeaclassthatyouwanttouseasthekeyofahashtable,youshouldoverridethehashCode()andequals()methods.– Don'tworryaboutthisatthemoment.
HashMap (exampleforStringmaptoint)
• Creation– Map<String, Integer> map = new HashMap<String, Integer>();
• Putstuffin– map.put(s, i); // associates key s with value i
• Getstuffout– map.get(s); // returns whatever value s is associated with
• Otherstuff– map.size(), map.containsKey(s), map.keySet(), map.remove(s)
Enhancedforloop
You can use the enhanced for loop to iterate through a map:
for (String key : map.keySet()) {int value = map.get(key);// do something with key and/or value
}
Trythis:memoized FibonacciinJava
• AddaHashMap<Integer,Integer>asastaticfieldtoyourclass.– ThiswillstorethecachedFibonaccivalues.
• AlteryourFibonaccimethodsoitdoesthefollowing:– Forfib(n):– ifn=0orn=1,returnn– Checkifnisakeyinthehashtable.
• Ifitis,getthecorrespondingvalueandreturnit.• Ifit'snot,then
– computev=fib(n-1)+fib(n-2)– putthemappingfromntovinthehashtable– returnv
HashSets
• ASet(ADT)isanunordered collectionofitems.– AListisanordered collectionofitems.
• JavahasaHashSet classthatimplementsthisADT.• SimilartoC++'sstd::setclass.
HashSet (exampleforints)
• Creation– HashSet<Integer> set = new HashSet<Integer>();
• Putstuffin– set.add(x); // adds x to the set
• Testifsomethingisintheset– set.contains(x); // returns true or false
• Remove something from the set– set.remove(x);
• Other stuff– set.size(), set.isEmpty(), set.clear()