01Everything is an Object.docx
- 文档编号:12073245
- 上传时间:2023-04-16
- 格式:DOCX
- 页数:18
- 大小:17.95KB
01Everything is an Object.docx
《01Everything is an Object.docx》由会员分享,可在线阅读,更多相关《01Everything is an Object.docx(18页珍藏版)》请在冰豆网上搜索。
01EverythingisanObject
EverythingisanObject
TosatisfyIDEslikeEclipse,wehaveincludedpackagestatementsforchapters
beforeAccessControl.Ifyouhavesolvedtheproblemsinthischapterwithout
usingpackagestatements,yoursolutionsarestillcorrect.
Exercise1
//:
object/E01_DefaultInitialization.java
/******************Exercise1*****************
*Createaclasscontaininganintandachar
*thatarenotinitialized.Printtheirvalues
*toverifythatJavaperformsdefault
*initialization.
***********************************************/
packageobject;
publicclassE01_DefaultInitialization{
inti;
charc;
publicE01_DefaultInitialization(){
System.out.println("i="+i);
System.out.println("c=["+c+']');
}
publicstaticvoidmain(String[]args){
newE01_DefaultInitialization();
}
}/*Output:
i=0
c=[]
*///:
~
Whenyouruntheprogramyou’llseethatbothvariablesaregivendefault
values:
0fortheint,anda“space”forthechar.
Exercise2
//:
object/E02_HelloWorld.java
10ThinkinginJava,4thEditionAnnotatedSolutionGuide
/******************Exercise2******************
*FollowtheHelloDate.javaexampleinthis
*chaptertocreatea"hello,world"programthat
*simplydisplaysthatstatement.Youneedonlya
*singlemethodinyourclass(the"main"onethat
*executeswhentheprogramstarts).Remember
*tomakeitstaticandtoincludetheargument
*list(eventhoughyoudon'tuseit).
*Compiletheprogramwithjavacandrunitusing
*java.Ifyouareusingadifferentdevelopment
*environmentthantheJDK,learnhowtocompile
*andrunprogramsinthatenvironment.
************************************************/
packageobject;
publicclassE02_HelloWorld{
publicstaticvoidmain(String[]args){
System.out.println("Hello,world!
");
}
}/*Output:
Hello,world!
*///:
~
Exercise3
//:
object/E03_ATypeName.java
/******************Exercise3******************
*TurnthecodefragmentsinvolvingATypeName
*intoaprogramthatcompilesand
*runs.
************************************************/
packageobject;
publicclassE03_ATypeName{
publicstaticvoidmain(String[]args){
E03_ATypeNamea=newE03_ATypeName();
}
}///:
~
Exercise4
//:
object/E04_DataOnly.java
/******************Exercise4******************
*TurntheDataOnlycodefragmentsintoa
*programthatcompilesandruns.
EverythingisanObject11
************************************************/
packageobject;
publicclassE04_DataOnly{
inti;
doubled;
booleanb;
publicstaticvoidmain(String[]args){
E04_DataOnlyd=newE04_DataOnly();
d.i=47;
d.d=1.1;
d.b=false;
}
}///:
~
Exercise5
//:
object/E05_DataOnly2.java
/******************Exercise5******************
*ModifyExercise4sothevalues
*ofthedatainDataOnlyareassignedtoand
*printedinmain().
************************************************/
packageobject;
publicclassE05_DataOnly2{
publicstaticvoidmain(String[]args){
E04_DataOnlyd=newE04_DataOnly();
d.i=47;
System.out.println("d.i="+d.i);
d.d=1.1;
System.out.println("d.d="+d.d);
d.b=false;
System.out.println("d.b="+d.b);
}
}/*Output:
d.i=47
d.d=1.1
d.b=false
*///:
~
Exercise6
//:
object/E06_Storage.java
/******************Exercise6******************
12ThinkinginJava,4thEditionAnnotatedSolutionGuide
*Writeaprogramthatincludesandcallsthe
*storage()methoddefinedasacodefragmentin
*thischapter.
************************************************/
packageobject;
publicclassE06_Storage{
Strings="Hello,World!
";
intstorage(Strings){
returns.length()*2;
}
voidprint(){
System.out.println("storage(s)="+storage(s));
}
publicstaticvoidmain(String[]args){
E06_Storagest=newE06_Storage();
st.print();
}
}/*Output:
storage(s)=26
*///:
~
Exercise7
//:
object/E07_Incrementable.java
/******************Exercise7******************
*TurntheIncrementablecodefragmentsintoa
*workingprogram.
************************************************/
packageobject;
classStaticTest{
staticinti=47;
}
publicclassE07_Incrementable{
staticvoidincrement(){StaticTest.i++;}
publicstaticvoidmain(String[]args){
E07_Incrementablesf=newE07_Incrementable();
sf.increment();
E07_Incrementable.increment();
increment();
}
}///:
~
EverythingisanObject13
Youcancallincrement()byitself,becauseastaticmethod(main(),inthis
case)cancallanotherstaticmethodwithoutqualification.
Exercise8
//:
object/E08_StaticTest.java
/******************Exercise8******************
*Writeaprogramtodemonstratethatno
*matterhowmanyobjectsyoucreateofa
*particularclass,thereisonlyoneinstance
*ofaparticularstaticfieldinthatclass.
************************************************/
packageobject;
publicclassE08_StaticTest{
staticinti=47;
publicstaticvoidmain(String[]args){
E08_StaticTestst1=newE08_StaticTest();
E08_StaticTestst2=newE08_StaticTest();
System.out.println(st1.i+"=="+st2.i);
st1.i++;
System.out.println(st1.i+"=="+st2.i);
}
}/*Output:
47==47
48==48
*///:
~
TheoutputshowsthatbothinstancesofE08_StaticTestsharethesamestatic
field.Weincrementedthesharedfieldthroughthefirstinstanceandtheeffect
wasvisibleinthesecondinstance.
Exercise9
//:
object/E09_AutoboxingTest.java
/******************Exercise9******************
*Writeaprogramtodemonstratethat
*autoboxingworksforalltheprimitivetypes
*andtheirwrappers.
************************************************/
packageobject;
publicclassE09_AutoboxingTest{
publicstaticvoidmain(String[]args){
14ThinkinginJava,4thEditionAnnotatedSolutionGuide
Byteby=1;
bytebt=by;
System.out.println("byte="+bt);
Shortsh=1;
shorts=sh;
System.out.println("short="+s);
Integerin=1;
inti=in;
System.out.println("int="+i);
Longlo=1L;
longl=lo;
System.out.println("long="+l);
Booleanbo=true;
booleanb=bo;
System.out.println("boolean="+b);
Characterch='x';
charc=ch;
System.out.println("char="+c);
Floatfl=1.0f;
floatf=fl;
System.out.println("float="+f);
Doubledb=1.0d;
doubled=db;
System.out.println("double="+d);
}
}/*Output:
byte=1
short=1
int=1
long=1
boolean=true
char=x
float=1.0
double=1.0
*///:
~
ThetermsAutoboxingandAutounboxingappearoftenintheliterature.The
onlydifferenceisthedirectionoftheconversion:
autoboxingconvertsfromthe
primitivetypetothewrapperobject,andautounboxingconvertsfromthe
wrappedtypetotheprimitivetype.
Exercise10
//:
object/E10_ShowArgs.java
//{Args:
ABC}
/******************Exercise10****************
EverythingisanObject15
*Writeaprogramthatprintsthreearguments
*takenfromthecommandline.
*You'llneedtoindexintothecommand-line
*arrayofStrings.
***********************************************/
packageobject;
publicclassE10_ShowArgs{
publicstaticvoidmain(String[]args){
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);
}
}/*Output:
A
B
C
*///:
~
Remember,whenyouwanttogetanargumentfromthecommandline:
•ArgumentsareprovidedinaStringarray.
•args[0]isthefirstcommand-lineargumentandnotthenameofthe
program(asitisinC).
•You’llcausearuntimeexceptionifyouruntheprogramwithoutenough
arguments.
Youcantestforthelengthofthecommand-lineargumentarraylikethis:
//:
object/E10_ShowArgs2.java
//{Args:
ABC}
packageobject;
publicclassE10_ShowArgs2{
publicstaticvoidmain(String[]args){
if(args.length<3){
System.err.println("Need3arguments");
System.exit
(1);
}
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);
}
}/*Output:
A
B
16ThinkinginJava,4thEditionAnnotatedSolutionGuide
C
*///:
~
System.exit()terminatestheprogramandpassesitsargumentbacktothe
operatingsystemasastatuscode.(Withmostoperatingsystems,anon-zero
statuscodeindicatesthattheprogramexecutionfailed.)Typically,yousend
errormessagestoSystem.err,asshownabove.
Exercise11
//:
object/E11_AllTheColorsOfTheRainbow.java
/******************Exercise11*****************
*TurntheAllTheColorsOfTheRainbowexampleinto
*aprogramthatcompilesandruns.
************************************************/
packageobject;
publicclassE11_AllTheColorsOfTheRainbow{
intanIntegerRepresentingColors;
voidchangeTheHueOfTheColor(intnewHue){
anIntegerRepresentingColors=newHue;
}
publicstaticvoidmain(String[]args){
E11_AllTheColorsOfTheRainbowall=
newE11_AllTheColorsOfTheRainbow();
all.changeTheHueOfTheColor(27);
}
}///:
~
Exercise12
//:
object/E12_LeftToReader.java
/******************Exercise12*****************
*Findthecodeforthesecondversionof
*HelloDate.java,thesimplecomment-
*documentationexample.ExecuteJavadoconthe
*fileandviewtheresultswithyourWebbrowser.
************************************************/
packageobject;
publicclassE12_LeftToReader{
publicstaticvoidmain(Stringargs[]){
System.out.println("Exerciselefttoreader");
}
}///:
~
EverythingisanObject17
NotethatJavadocdoesn’tautomaticallycreatethedestinationdirectory.
ConsulttheJavadocreferenceintheJDKdocumentationtolearnthemany
usesofJavadoc.
Exercise13
//:
object/E13_LeftToReader.java
/******************Exercise13*****************
*RunDocumentation1.java,Documentation2.java,
*andDocumentation3.javathroughJavadoc.Verify
*theresultingdocumentationwithyourWeb
*
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 01Everything is an Object 01 Everything