Upload
others
View
69
Download
0
Embed Size (px)
Citation preview
JavaforC#programmers
andviceversa…
Acknowledgement:somecontenttakenfromhttp://www.javacamp.org/javavscsharp
0:Generalconsiderations
HistoryAgreatmanyJavadevelopersconsideredMicrosoft'sVisualJ++tobethemostproductiveJavaIDE(integrateddevelopmentenvironment)onthemarket.Thesettlementofalawsuit(2001)broughtbySunMicrosystemsstoppedVisualJ++'sevolutioninitstracksandappearedtoendMicrosoft'sinvolvementwithJava.MicrosoftthenproducedJ#,andmoreorlessatthesametimeC#...Curiosity:Duetotechnicallimitationsofdisplay(standardfonts,browsers,etc.)andthefactthatthesharpsymbol(U+266F♯MUSICSHARPSIGN(HTML♯))isnotpresentonmostkeyboardlayouts,thenumbersign(U+0023#NUMBERSIGN(HTML#))waschosentoapproximatethesharpsymbolinthewrittennameoftheprogramminglanguage.
Proprietarylanguage?
C#isdefinedbyECMAandISOstandards,whereasJavaisproprietary,thoughlargelycontrolledthroughanopencommunityprocess.TheC#APIiscompletelycontrolledbyMicrosoft,whereastheJavaAPIismanagedthroughanopencommunityprocess.
Structure
Technologystack
JDK-JREJRE:JavaRuntimeEnvironment.ItisbasicallytheJavaVirtualMachinewhereyourJavaprogramsrunon.ItalsoincludesbrowserpluginsforAppletexecution.JDK:It'sthefullfeaturedSoftwareDevelopmentKitforJava,includingJRE,andthecompilersandtools(likeJavaDoc,andJavaDebugger)tocreateandcompileprograms.Usually,whenyouonlycareaboutrunningJavaprogramsonyourbrowserorcomputeryouwillonlyinstallJRE.It'sallyouneed.Ontheotherhand,ifyouareplanningtodosomeJavaprogramming,youwillalsoneedJDK.
JDK-JRE"TheJRE"isbasicallyabunchofdirectorieswithJava-relatedfiles:/binwithexecutableprogramslikejavaand(forWindows)javaw,whichareessentiallytheprogramthatistheJavavirtualmachine;/libwithalargenumberofsupportingfiles:Somejars,configurationfiles,propertyfiles,fonts,sounds,icons...allthe"trimmings"ofJava.Mostimportantarert.jarandapossiblyafewofitssiblings,whichcontainthe"javaAPI,"i.e.theJavalibrarycode.Somewherearehiddensome.DLLs(forWindows)or.so's(Unix/Linux)withsupporting,oftensystem-specificnativebinarycode.TheJDKisalsoasetofdirectories.ItlooksalotliketheJREbutitcontainsadirectory(calledJRE)withacompleteJRE,andithasanumberofdevelopmenttools,mostimportantlytheJavacompilerjavacinitsbindirectory.
JDK-JRE
1:Contactpoints
Wow,it’sthesamething!
Thelanguagessharemanyfeatures:
• Objectorientation• Sameancestors(C,C++)=>samegrammar
– SomepeoplesayC#isderivedfromJava• Heap-basedclasses(butC#alsosupportsstack-basedclasses,
calledvaluetypes)• Garbagecollection• Stringclass(stringsareimmutable)• Noglobalmethodsandvariables• Initializationofinstanceandstaticvariables.• Superclass(baseclass)constructorcall,andconstructorchaining
(calltoaconstructorfrominsideanotherconstructor)• Valuetypesforprimitivedatatypes,referencetypesforobjects.
2:Trivialdifferences:syntaxonly
trivialbutannoyingdifferences…
mainJava C#
publicstaticvoidmain(String[]args){…} staticvoidMain(string[]args){…}
staticvoidMain(){…}
staticintMain(string[]args){…}
staticintMain(){…}
Note:asaconvention:methodnamesarelowercaseinJavaanduppercaseinC#classnamesareuppercaseinJavaandlowercaseinC#
PrintstatementsJava C#
System.out.println("Helloworld!"); System.Console.WriteLine("Helloworld!");
Console.WriteLine("Helloagain!");
Note:asaconvention:methodnamesarelowercaseinJavaanduppercaseinC#classnamesareuppercaseinJavaandlowercaseinC#
keywords
gotostrictfp
switch
• Nofall-throughinC#,exeptforvoidstatements
• NowusablewithstringsalsoinJava˜
Java C#
switch(i){case1:case2:a=1;case3:b=2;break;case4-7:b=9;break;default:c=3;}
<=fallbackisnotallowedfornon-emptycases(breakismissing)
SwitchstatementswithStringcaseshavebeenimplementedsinceJavaSE7
Arraydeclarations
MultidimensionalarraysinJavaandC#arejagged int[][]j2 = new int[3][]; j2[0] = new int[] {1, 2, 3}; j2[1] = new int[] {1, 2, 3, 4, 5, 6}; j2[2]= new int[10];C#alsohasrectangularbidimensionalarrays(moreefficient)
Java C#
int[]iArray=newint[100];floatfArray[]=newfloat[100];
int[]iArray=newint[100];
int[][][] a3 = new int[20][20][30]; int[][][] a3 = new int[20][20][30];int[,]myRectangularArray=newint[rows,columns];
for-foreach
Java C#
int []k={1,2,3}; for (int z:k){ System.out.println(z); }
int []k={1,2,3}; foreach(int z ink){ System.Console.WriteLine(z); }
for(objecto:collection){…} foreach(objectoincollection){…}
ConstantsJava C#
staticfinaldoublePI=3.1415926535; constdoublePI=3.1415926535;
finalintN=2; readonlyintZ=24;
C#:Whentheconstantneedstobeinitializedatrun-timeusethereadonlykeywordinsteadofconst.
Java:Constantswithvalueswhichmaybedifferentfordifferentinstancesarenotstatic.
final/readonlyvarscanonlybesetatdeclarationtimeorintheconstructor
Packages-namespaces
TheC#packagestructureisdefinedusingnamespaces(justlikeJava),butthenamespacesdoNOThavetoreflectthedirectorystructure.C#'snamespacesaremoresimilartothoseinC++.UnlikeJava,thenamespacedoesnotspecifythelocationofthesourcefile.(Actually,it'snotstrictlynecessaryforaJavasourcefilelocationtomirroritspackagedirectorystructure.)C#hastheabilitytoaliasnamespaces.
Java C#
package namespace
import using
Packages-namespacesnestingOnlyinC#:namespacesyntaxalsoallowstonestnamespacesusingSystem;namespaceOne{publicclassMyClass{…}/*One.MyClass*/namespaceTwo{publicclassMyOtherClass{…}/*One.Two.MyOtherClass*/}//endofnamespaceTwo}//endofnamespaceOne
Assemblies
Java C#
AssembliesarestoredasJARarchives(JavaARchive:zipformatwithamanifest).AJARcancontainalibrary,orcanbean“executable”file.SomeJARarespecializedfordeploymentincontainers:WAR(WebARchive)EJB-JAR(EntityBeansArchives)EAR(EnterpriseARchive)
AssembliesareusuallystoredasEXEsorDLLs
Boxing-UnboxingJava C#
inti=123;Objecto=i;//Objecto=123;
inti=123;objecto=i;//objecto=123;
Objecto = 123;inti = (Integer)o;//butalsoIntegero = 123;inti = o;
objecto = 123;inti = (int)o;
InC#unboxingisalwaysexplicit
varargsJava C#
voidf(Stringtitle,Integer…args) voidf(stringtitle,paramsint[]args)
InvokingGarbageCollectorJava C#
System.gc() GC.Collect()
Concurrency-synchronizationJava C#
synchronized(this){...} lock(this){...}
synchronizedvoidmethod(){...} [MethodImpl(MethodImplOptions.Synchronized)]voidMethod(){...}
Serialization
[Serializable]:isusedtomarkaclassasserializableandissimilartoaJavaclassimplementingtheSerializableinterface.Put[ScriptIgnore]or[NonSerialized]attributeonthepropertyanditwillnotbeserialized.(transientinJava)
Java C#
MyClassimplementsSerializable{transientObjectx;…}
[Serializable]myClass{[ScriptIgnore]objectx;…}
ClassloadingJava C#
Classx=Class.forName(“class_name”);x.getInstance();ClassLoader.getResources()
Activator.CreateInstance(Typet)Assembly.Load()
Run-timetypeidentificationJava C#
if(xinstanceofMyClass)MyClassmc=(MyClass)x;
if(xisMyClass)MyClassmc=(MyClass)x;
MetadataJava C#
ClassClassklass=X.class;//callonclassClassklass=x.getClass();//calloninstance
TypeTypetype=typeof(X);//callonclassTypetype=i.GetType();//calloninstance
MetainformationJava C#
@Annotation [Attribute]
3:JavafeaturesabsentinC#
Thereisnosuchathingas…
CrossPlatformPortability:WriteOnce,RunAnywhere
NestedclassesClassdeclarationinsideanotherclass.Javainnerclass:foreachinstanceoftheenclosingclassthereexistsacorrespondinginstanceoftheinnerclassthathasaccesstotheenclosingclass'sinstancevariablesandcontainsnostaticmethods.Javastaticnestedclass:thenestedclasshasaccesstothestaticmembersandmethodsoftheenclosingclass.C#ONLYhasstaticnestedclasses.
Anonymousinnerclasses
btn.setOnAction(newEventHandler<ActionEvent>(){@Overridepublicvoidhandle(ActionEventevent){System.out.println("HelloWorld!");}});
4:Simplebutrelevantdifferences
Reallyimportantdifferences…
Primitivedatatypes• NoteveryC#primitivetypehasacorrespondingtypeinJava:Javadoesnothavetheunsignedtypes(ulong,uint,ushortandbyte).
• Thecorrespondingoneshavathesamename(exceptforbyte:thebytetypeinJavaissignedandisthusanalagoustothesbytetypeinC#andnotthebytetype).
• C#alsohasisthedecimaltype,atypewhichstoresdecimalnumberswithoutroundingerrors(atthecostofmorespaceandlessspeed).
• NOTE:primitivedatatypesinC#aresubclassesofobject,inJavatheyarenot!
Primitivedatatypes
• NOTE:primitivedatatypesinC#aresubclassesofobject,inJavatheyarenot!
• ThismeansthatanintinC#inheritsallthemethodsofobject.
• It’simportanttorealize,however,thattheprimitivetypesarestillvaluetypes.Boxing(theconversionofavaluetypetoareferencetype)occursinbothC#andJava.
Bignumbers
BothJavaandC#haveBigInteger.It’sforprecision(large)integers.Javaalsohas,butC#hasn’t,BigDecimal.
AccessmodifierJava C#
public Accessnotlimited Accessnotlimited
protected Accesslimitedtothepackageandtosubclassesalsoinadifferentpackage
Accesslimitedtothecontainingclassanditssubclasses
protectedinternal Accesslimitedtothisprogramortypesderivedfromthecontainingclass
internal Accesslimitedtothisprogram(assembly)
(noaccessmodifier) Accesslimitedtothepackage
Sameasprivate
private Accesslimitedtothecontainingtype
Accesslimitedtothecontainingtype
FriendAssembly(C#only)
Thefriendassemblyfeatureallowsaninternaltypeorinternalmemberofanassemblytobeaccessedfromanotherassembly.Togiveoneassemblyaccesstoanotherassembly'sinternaltypesandmembers,the[InternalsVisibleToAttribute]attributeisused.
InheritanceJava C#
classBextendsAimplementsComparable{…}
classB:A,IComparable
Note:-differentsyntaxforInterfaceinheritanceandclassinheritanceinJava- UsuallyinterfacesnamesstartwithIinC#- ForbothJavaandC#inheritanceis
- SINGLEforclasses- MULTIPLEforInterfaces
Java C#
EverythingderivesfromObject.Thisincludesclassesyoucreate,notincludingprimitivetypes.
EverythingultimatelyderivesfromObject.Thisincludesclassesyoucreate,aswellasvaluetypessuchasintorstructs.
Partialclasses:aC#onlyfeature
• WithC#youcandefineaclassacrossmultiplefiles.
• Therealuseofthisiswhenyouaregeneratingcodeandyouwanttobeabletohavepartofaclassgenerated,butstillhavetheotherpartoftheclassmanuallycontrolledandversioned.
UnextendableclassesJava C#
finalclassB{…} sealedclassB{…}
StaticconstructorJava C#
ClassStaticInitTest{static{//calledbeforefirstuseofstaticclassSystem.out.println("Instaticconstructor");}…}
ClassStaticInitTest{staticStaticInitTest(){Console.WriteLine("Instaticconstructor");}…}
DestructorNon-DeterministicObjectCleanup
Java C#
finalize() ~X()
ConstructorchainingJava C#
super() base()
publicclassChildextendsParent{publicChild(){super("param");System.out.println("ChildConstructor.");}… super.f();…}
publicclassChild:Parent{publicChild():base(”param"){Console.WriteLine("ChildConstructor.");}… base.f();…}
InC#,destructorsautomaticallycallthebaseclassdestructorafterexecuting,whichisnotthecaseinJava.
Constraintonpublicclasses
InJava,therecanonlybeoneclasspersourcefilethathaspublicaccessanditmusthavethesamenameasthesourcefile.C#doesnothavesuchconstraint.
VirtualmethodsJava C#
Allmethodsarebydefaultvirtualandyoucanoverridethem(dynamicbinding).Javahasstaticbindingfor:final,staticandprivatemethods.Youcanannotateoverridingmethods:@OverridepublicvoidmyMethod(){...}
Allmethodsarenon-virtual(staticbinding).Tooverrideamethodintheparentclass,makesurethemethodoftheparentclassisdefinedasvirtualusingthevirtualkeyword.classMyParentClass{publicvirtualvoidMyMethod(){...}}Inthechildclass,themethodmustusetheoverridekeyword.classMyChildClass:MyParentClass{publicoverridevoidMyMethod(){...}}
Enumerations
• Javamadeenumerationsjustlikeclasses,excepttheydonothaveinheritance.
• C#enumerationsaremorealongthelinesofC/C++implementationsinwhichtheyarejustbasicallyintegers,buttheysupporttheToStringmethod,sotheycanreporttheirvalueasstring(suchas“North")andnotjustananinteger.
Java C#
enum,canhavefields,methodsandimplementinterfacesandaretypesafe
enum,cannothavemethods,fieldsorimplementinterfaces,nottypesafe
EqualitycheckJava C#
Valueequality:b == aReferenceequality(identity):b==a;Equalityforreferencetypes:overrideObject.equals(Object)overrideObject.hashcode()
Valueequality:b == aReferenceequality(identity):System.Object.ReferenceEquals(a,b);Equalityforreferencetypes:overrideObject.Equals(Object)overrideObject.GetHashCode()Optionallyoverloadthe==and!=operators
Generics• Although,theGenericsfeatureinbothC#andJavaissimilar
inconcepttotemplatesinC++.• GenericsinJavaandC#lookeverysimilar,but
implementationsarehoweverquitedifferent.
• C#implementationisalsomoreefficient(doesn’tdoany
cast).
Java C#
thegenericfunctionalityisimplementedusingtypeerasure.Thegenerictypeinformationispresentatcompiletime,afterwhichitiserasedandallthetypedeclarationsarereplacedwithObject.Castsareautomaticallyinsertedintherightplaces.Hence,runtimeintrospectiondoesnotrevealthegeneric.
permitsfullruntimeintrospectionofgenerictypesandgenerictypeparameters(usefule.g.forinstancecreationandarraycreation).
Weakreferences
Foranexplanationseealso:https://web.archive.org/web/20061130103858/http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html
Java C#
someCollection.add(inewWeakReference(newMyData(i));Javaalsohas:• SoftReference• PhantomReference
someCollection.Add(newWeakReference(newMyData(i));
Differentoperators:>>>and->Javaonly:The>>>operatoristheunsignedrightbit-shift.Iteffectivelydividestheoperandby2tothepoweroftherightoperand.Thedifferencebetween>>and>>>wouldonlyshowupwhenshiftingnegativenumbers.The>>operatorshiftsa1bitintothemostsignificantbitifitwasa1,andthe>>>shiftsina0regardless.C#only:The->operatorcombinespointerdereferencingandmemberaccess(asinC,C++).The->operatorcanbeusedonlyincodethatismarkedasunsafe.The->operatorcannotbeoverloaded.
Checked-uncheckedexceptions
Thecheckedexceptionsthatamethodmayraisearepartofthemethod'ssignature.Forinstance,ifamethodmightthrowanIOException,itmustdeclarethisfactexplicitlyinitsmethodsignature.Failuretodosoraisesacompile-timeerror.C#doesnotincludecheckedexceptions,Javadoes.
throw/throws
Nullabletypes(C#)AnullabletypesisaninstanceoftheSystem.Nullabletype.Anullabletypecanrepresentthenormalrangeofvaluesforanunderlyingvaluetypeaswellasthenullvalue.Forexample,thetypeNullable<bool>canrepresentthevaluestrue,falseandnull.Anullabletypecanbedeclaredbyappendingtheoperator'?'tothenameofavaluetypewhendeclaringthevariable.bool?isequivalenttoNullable<bool>.
nullcoalescingoperator:??(C#)stringpageTitle=suppliedTitle??"DefaultTitle";//isequivalenttostringpageTitle=(suppliedTitle!=null)?suppliedTitle:"DefaultTitle";//andisequivalenttostringpageTitle;if(suppliedTitle!=null)pageTitle=suppliedTitle;elsepageTitle="DefaultTitle”;
SameinJava(Optional)
StringmyTitle=null;Optional<String>suppliedTitle=Optional.ofNullable(myTitle);Stringtitle=suppliedTitle.orElse("DefaultTitle");System.out.println(title);//also:Stringtitle2=suppliedTitle.orElseGet(()->{returnnewString("DefaultTitle2");});System.out.println(title2);
Optionalhasseveralothermethods
DocumentationgenerationJava C#
***Calculatesthesquareofanumber.*@paramnumthenumbertocalculate.*@returnthesquareofthenumber.*@exceptionNumberTooBigExceptionthisoccursifthesquareofthenumber*istoobigtobestoredinanint.*/publicstaticintsquare(intnum)throwsNumberTooBigException{}
///<summary>Calculatesthesquareofanumber.</summary>///<paramname="num">Thenumbertocalculate.</param>///<return>Thesquareofthenumber.</return>///<exception>NumberTooBigException-thisoccursifthesquareofthenumber///istoobigtobestoredinanint.</exception>publicstaticintsquare(intnum){}
JavadocvsC#XML
C#XMLismorelimitedthanJavadoc
DocumentationgenerationJavadocallowsonetodocumentthefollowingmetadataaboutamethod:• Descriptionofthemethod.• Exceptionsthrownbythemethod.• Parametersthemethodaccepts• Returntypeofthemethod.• Associatedmethodsandmembers.• IndicationastowhethertheAPIhasbeendeprecatedornot.• VersionoftheAPIthemethodwasfirstadded.• Thedeprecatedinformationisalsousedbythecompilerwhichissuesawarningifacalltoa
methodmarkedwiththedeprecatedtagisencounteredduringcompilation.Javadocalsoprovidesthefollowinginformationautomatically:• InheritedAPI• Listofderivedclasses• Listofimplementingclassesforinterfaces• Serializedformoftheclass• Alphabeticalclasslisting.• Packagehierarchyinatreeformat.
5:C#featuresabsentinJava
Thereisnosuchathingas…
Preprocessordirectives
• C#hasproprocessordirectives(similartothoseofCandC++)
Althoughthecompilerdoesn'thaveaseparatepreprocessor,thedirectivesareprocessedasiftherewereone.Theyareusedtohelpinconditionalcompilation.UnlikeCandC++directives,youcannotusethesedirectivestocreatemacros.
Implicitlytypedvariables
vari=10;//implicitlytypedinti=10;//explicitlytypedNote:inJavatypeinferenceisonlydonewithgenerics,buttheotherwayround:LinkedList<String>x=newLinkedList<>();
Properties(C#only)Java C#
publicclassPropHolder{privateintsomeProperty=0;publicintgetSomeProperty(){returnsomeProperty;}publicvoidsetSomeProperty(intx){someProperty=x;}}publicclassPropertyTester{publicstaticvoidmain(String[]args){PropHolderpropHold=newPropHolder();propHold.setSomeProperty(5);System.out.println("PropertyValue:",propHold.getSomeProperty);}}
publicclassPropHolder{privateintsomeProperty=0;publicintSomeProperty{get{returnsomeProperty;}set{someProperty=value;}}}publicclassPropertyTester{publicstaticvoidMain(string[]args){PropHolderpropHold=newPropHolder();propHold.SomeProperty=5;Console.WriteLine("PropertyValue:{0}",propHold.SomeProperty);}}
YoucanasktheIDEtocreategettersandsettersforyou
Properties(C#only)
Totheclient,apropertylookslikeamembervariable,buttotheimplementoroftheclassitlookslikeamethod.Itallowsyoutotalencapsulationanddatahidingwhilegivingyourclientseasyaccesstothemembers.Thevalueisimplicitlyavailabletotheproperty.Youcanhavereadonlyandwriteonlyproperties.
Verbatimstrings
Also,somedifferenceinescapesequences:
Java C#
Stringpath="C:\\MyDocuments\\";//ThereisnoverbatimstringinJava
stringpath="C:\\MyDocuments\\";//canbewrittenwithverbatimstringlike:stringpath=@"C:\MyDocuments\";
Outparameters(passbyreference)C#only:theoutkeyword,whichindicatesthatyoumaypassinuninitializedvariablesandtheywillbepassedbyreference.Thecallingmethodshouldmarkoutkeyword.classTest{staticvoidDivide(inta,intb,outintresult,outintremainder){result=a/b;remainder=a%b;}staticvoidMain(){for(inti=1;i<10;i++)for(intj=1;j<10;j++){intans,r;Divide(i,j,outans,outr);Console.WriteLine("{0}/{1}={2}r{3}",i,j,ans,r);}}}
StructstructPoint{publicintx,y;publicPoint(intx,inty){this.x=x;this.y=y;}}Pointa=newPoint(10,10);Pointb=a;a.x=100;System.Console.WriteLine(b.x);
Astructisauser-definedvaluetype.StructsinC#areusedsimilarlytoclasses,exceptthatitcan'tinheritfromanyclass,norcananyclassinheritfromit(theyare“sealed”andtheimplicitbaseclassisSystem.ValueType,whichisderivedfromObject.Theycancontainconstructors,constants,methodsandmore.structisnotareferencetype!
AliasesTheusingkeywordcanbeusedtoaliasthefullyqualifiednameforatypesimilartothewaytypedefisusedinCandC++.Thisisusefulincreatingreadablecodewherethefullyqualifiednameofaclassisneededtoresolvenamespaceconflicts.usingTerminal=System.Console;classTest{publicstaticvoidMain(string[]args){//Terminal.WriteLineisequivalenttoSystem.Console.WritelineTerminal.WriteLine(”hello");}}
Staticclasses
Astaticclassisaclassthathasnoinstancemembers,noinstanceconstructorsandcannotbeusedasabaseclass.(e.g.System.Mathclass)
OverflowdetectionC#providestheoptiontoexplicitlydetectorignoreoverflowconditionsinexpressionsandtypeconversions./* overflow detected only if /checked compiler option on */byte a = (byte) num; checked{ byte b = (byte) num; /* overflow ALWAYS detected */ } unchecked{ byte c = (byte) num; /* overflow NEVER detected */ }
PointersandunsafecodeItispossibletohaveinC++andC-likepointertypeswithinan“unsafecontext”(alotofruntimecheckingisthendisabled).public static unsafe void Sort(int* array, int size){ for(int i= 0; i <size - 1; i++) for(int j = i + 1; j <<size; j++) if(array[i] > array[j]) Swap(&array[i], &array[j]); }
Sincegarbagecollectionmayrelocatemanagedvariablesduringtheexecutionofaprogram,thefixedkeywordisprovidedsothattheaddressofamanagedvariableispinnedduringtheexecutionofthepartsoftheprogramwithinthefixedblock.
DeterministicObjectCleanupByimplementingtheinterfaceiDisposeyoucanexposeamethod(Dispose)toactuallydeleteanobjectwithoutwaitingfortheGarbageCollectortocome.Also,youcantelltheGCtokeepclearfromthisobject:GC.SuppressFinalize(this);Seehttps://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface
ExplicitinterfaceAclassmayimplementindifferentwayamethodbelongingtodifferentinterfaces.Theimplementingmethodmustbeprivate,andcanonlybecalledbycastingontheinterface.
publicclassSampleClass:IControl,Isurface{voidIControl.Paint(){System.Console.WriteLine("IControl.Paint");}voidISurface.Paint(){System.Console.WriteLine("ISurface.Paint");}}
//CallthePaintmethodsfromMain.SampleClassobj=newSampleClass();//obj.Paint();//Compilererror.IControlc=(IControl)obj;//CallsIControl.PaintonSampleClass.c.Paint();ISurfaces=(ISurface)obj;//CallsISurface.PaintonSampleClass.s.Paint();
Output:IControl.PaintISurface.Paint
Operatoroverloading
Javadoesnotincludeoperatoroverloading,becauseabuseofoperatoroverloadingcanleadtocodethatishardertounderstandanddebug.(butthelanguagedefinesthe+operatorforStrings)C#allowsoperatoroverloading,which,whenusedcarefully,canmakecodeterserandmorereadable.
Example:+overloading
publicstaticBoxoperator+(Boxb,Boxc){Boxbox=newBox();box.length=b.length+c.length;box.width=b.width+c.width;returnbox;}
Someoperatorscannotbeoverloaded:Theconditionallogicaloperators:&&,||Theassignmentoperators:=,+=,-=,*=,/=,%=.,?:,->,new,is,sizeof,typeof
Example:==overloadingpublicclassScore:Icomparable{intvalue;publicScore(intscore){value=score;}publicstaticbooloperator==(Scorex,Scorey){returnx.value==y.value;}publicstaticbooloperator!=(Scorex,Scorey){returnx.value!=y.value;}publicintCompareTo(objecto){returnvalue-((Score)o).value;}}Scorea=newScore(5);Scoreb=newScore(5);Objectc=a;System.Console.WriteLine(((IComparable)c).CompareTo(a));//0System.Console.WriteLine((object)a==(object)b;//falseSystem.Console.WriteLine(a==b);//true
Someoperatorsmustberedefinedinpairs:!=and==>and<>=and<=
Indexer([]overloading)Indexersallowinstancesofaclassorstructtobeindexedjustlikearrays.Theindexedvaluecanbesetorretrievedwithoutexplicitlyspecifyingatypeorinstancemember.Usefule.g.todefinearray-likestuctureswithnon-numericindexes.
classDayCollection{string[]days={"Sun","Mon","Tues","Wed","Thurs","Fri","Sat"};privateintGetDay(stringtestDay){for(intj=0;j<days.Length;j++){if(days[j]==testDay){returnj;}}thrownewSystem.ArgumentOutOfRangeException(testDay,”unecognizedstring");}publicintthis[stringday]{get{return(GetDay(day));}}}
varweek=newDayCollection();System.Console.WriteLine(week["Fri"]);
(examplefromdocs.microsoft.com)
DelegatesDelegatesareamechanismforprovidingcallbackfunctions(similartofunctionpointersinCorfunctorsinC++).//delegatedeclaration,similartoafunctionpointerdeclarationpublicdelegatevoidCallbackFunction(Dogd);//functioncompatiblewithdelegatedeclarationpublicstaticvoidBark(Dogd){
Console.WriteLine(“{0}saysWOOF”,d);}//createdelegateusingdelegateinferenceCallbackFunctionmyCallback=Bark;myCallback(fido);//invokeit
Anonymousmethods
Gohandinhandwithdelegates:CallbackFunctioncf=delegate(Dogd){Console.WriteLine(“{0}saysWOOF”,d);}cf(fido);
Lambdaexpressions(alsoinJava)delegatevoidX();XinstanceOfX;instanceOfX=delegate(){code};instanceOfX=()=>{code};//alternative,usinglambdaexpressionLambdaexpressionsarealsoavailableinJava()->{code};Seealsohttps://blogs.msdn.microsoft.com/ericlippert/2007/01/10/lambda-expressions-vs-anonymous-methods-part-one/
6:Andthe,ofcourse,theAPI…
Thisisbig!
APIs(Java)
JavaAPIs
JavaProgrammingLanguage
JavaVirtualMachine
JavaCommerce™
JavaBeans
JavaSecurity™
JavaManagement
JavaMedia
JavaServer™
JavaEnterprise
e.g.:collectionsJava C#
TheJavacollectionsframeworkconsistsofalargenumberoftheclassesandinterfacesinthejava.utilpackage.Itsclasseshavebeenretrofittedtosupportgenerics.TheJavacollectionsframeworkhasanumberofalgorithmsformanipulatingtheelementswithinitscollections,suchas:performssortsandbinarysearches-findthelargest/smallestelementbasedonsomeComparator,findsublistswithinalist,reversethecontentsofalist,shufflethecontentsofalist,createimmutableversionsofacollection.
TheSystems.Collectionsnamespacecontains:• interfacesandabstractclassesthat
representabstractdatatypessuchasIList,IEnumerable,IDictionary,ICollection,andCollectionBase
• concreteimplementationsofdatastructuressuchasArrayList,Stack,Queue,HashTableandSortedList.
TheSystem.Collections.Genericnamespacecontainsgenericimplementationsoftheabove.