仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1165|回复: 19
打印 上一主题 下一主题

[学习教程] JAVA网页设计JAVA静态变量

[复制链接]
透明 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:43:01 | 显示全部楼层 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
在1995年5月23日以“Java”的名称正式发布了。变量|静态JAVA的静态变量相称于类字段,而不必了解为对象字段。



--------------------------------------------------------------------------------
StaticFieldsandMethods
Inallsampleprogramsthatyouhaveseen,themainmethodistaggedwiththestaticmodifier.Wearenowreadytodiscussthemeaningofthismodifier.

StaticFields
Ifyoudefineafieldasstatic,thenthereisonlyonesuchfieldperclass.Incontrast,eachobjecthasitsowncopyofallinstancefields.Forexample,letssupposewewanttoassignauniqueidentificationnumbertoeachemployee.WeaddaninstancefieldidandastaticfieldnextIdtotheEmployeeclass:

classEmployee
{
...
privateintid;
privatestaticintnextId=1;
}

Now,everyemployeeobjecthasitsownidfield,butthereisonlyonenextIdfieldthatissharedamongallinstancesoftheclass.Letsputitanotherway.IfthereareonethousandobjectsoftheEmployeeclass,thenthereareonethousandinstancefieldsid,oneforeachobject.ButthereisasinglestaticfieldnextId.Eveniftherearenoemployeeobjects,thestaticfieldnextIdispresent.Itbelongstotheclass,nottoanyindividualobject.


Inmostobject-orientedprogramminglanguages,staticfieldsarecalledclassfields.Theterm"static"isameaninglessholdoverfromC++.



Letsimplementasimplemethod:

publicvoidsetId()
{
id=nextId;
nextId++;
}

Supposeyousettheemployeeidentificationnumberforharry:

harry.setId();

Thentheidfieldofharryisset,andthevalueofthestaticfieldnextIdisincremented:

harry.id=...;
Employee.nextId++;

Constants
Staticvariablesarequiterare.However,staticconstantsaremorecommon.Forexample,theMathclassdefinesastaticconstant:

publicclassMath
{
...
publicstaticfinaldoublePI=3.14159265358979323846;
...
}

YoucanaccessthisconstantinyourprogramsasMath.PI.

Ifthekeywordstatichadbeenomitted,thenPIwouldhavebeenaninstancefieldoftheMathclass.Thatis,youwouldneedanobjectoftheMathclasstoaccessPI,andeveryobjectwouldhaveitsowncopyofPI.

AnotherstaticconstantthatyouhaveusedmanytimesisSystem.out.ItisdeclaredintheSystemclassas:

publicclassSystem
{
...
publicstaticfinalPrintStreamout=...;
...
}

Aswementionedseveraltimes,itisneveragoodideatohavepublicfieldsbecauseeveryonecanmodifythem.However,publicconstants(thatis,finalfields)areok.Sinceouthasbeendeclaredasfinal,youcannotreassignanotherprintstreamtoit:

out=newPrintStream(...);//ERROR--outisfinal


IfyoulookattheSystemclass,youwillnoticeamethodsetOutthatletsyousetSystem.outtoadifferentstream.Youmaywonderhowthatmethodcanchangethevalueofafinalvariable.However,thesetOutmethodisanativemethod,notimplementedintheJavaprogramminglanguage.NativemethodscanbypasstheaccesscontrolmechanismsoftheJavalanguage.Thisisaveryunusualworkaroundthatyoushouldnotemulateinyourownprograms.



StaticMethods
Staticmethodsaremethodsthatdonotoperateonobjects.Forexample,thepowmethodoftheMathclassisastaticmethod.Theexpression:

Math.pow(x,y)

computesthepowerxy.ItdoesnotuseanyMathobjecttocarryoutitstask.Inotherwords,ithasnoimplicitparameter.

Inotherwords,youcanthinkofstaticmethodsasmethodsthatdonthaveathisparameter.

Becausestaticmethodsdontoperateonobjects,youcannotaccessinstancefieldsfromastaticmethod.Butstaticmethodscanaccessthestaticfieldsintheirclass.Hereisanexampleofsuchastaticmethod:

publicstaticintgetNextId()
{
returnnextId;//returnsstaticfield
}

Tocallthismethod,yousupplythenameoftheclass:

intn=Employee.getNextId();

Couldyouhaveomittedthekeywordstaticforthismethod?Yes,butthenyouwouldneedtohaveanobjectreferenceoftypeEmployeetoinvokethemethod.


Itislegaltouseanobjecttocallastaticmethod.Forexample,ifharryisanEmployeeobject,thenyoucancallharry.getNextId()insteadofEmployee.getnextId().However,wefindthatnotationconfusing.ThegetNextIdmethoddoesntlookatharryatalltocomputetheresult.Werecommendthatyouuseclassnames,notobjects,toinvokestaticmethods.



Youusestaticmethodsintwosituations:

Whenamethoddoesntneedtoaccesstheobjectstatebecauseallneededparametersaresuppliedasexplicitparameters(example:Math.pow);

Whenamethodonlyneedstoaccessstaticfieldsoftheclass(example:Employee.getNextId).


StaticfieldsandmethodshavethesamefunctionalityinJavaandC++.However,thesyntaxisslightlydifferent.InC++,youusethe::operatortoaccessastaticfieldormethodoutsideitsscope,suchasMath::PI.

Theterm"static"hasacurioushistory.Atfirst,thekeywordstaticwasintroducedinCtodenotelocalvariablesthatdontgoawaywhenexitingablock.Inthatcontext,theterm"static"makessense:thevariablestaysaroundandisstilltherewhentheblockisenteredagain.ThenstaticgotasecondmeaninginC,todenoteglobalvariablesandfunctionsthatcannotbeaccessedfromotherfiles.Thekeywordstaticwassimplyreused,toavoidintroducinganewkeyword.Finally,C++reusedthekeywordforathird,unrelatedinterpretation,todenotevariablesandfunctionsthatbelongtoaclassbutnottoanyparticularobjectoftheclass.ThatisthesamemeaningthatthekeywordhasinJava.



FactoryMethods
Hereisanothercommonuseforstaticmethods.Considerthemethods

NumberFormat.getNumberInstance()
NumberFormat.getCurrencyInstance()

thatwediscussedinChapter3.EachofthesemethodsreturnsanobjectoftypeNumberFormat.Forexample,

NumberFormatformatter=NumberFormat.getCurrencyInstance();
System.out.println(formatter.format(salary));
//printssalarywithcurrencysymbol

Asyounowknow,thesearestaticmethods―youcallthemonaclass,notanobject.However,theirpurposeistogenerateanobjectofthesameclass.Suchamethodiscalledafactorymethod.

Whydontweuseaconstructorinstead?Therearetworeasons.Youcantgivenamestoconstructors.Theconstructornameisalwaysthesameastheclassname.IntheNumberFormatexample,itmakessensetohavetwoseparatenamesforgettingnumberandcurrencyformatterobjects.Furthermore,thefactorymethodcanreturnanobjectofthetypeNumberFormat,oranobjectofasubclassthatinheritsfromNumberFormat.(SeeChapter5formoreoninheritance.)Aconstructordoesnothavethatflexibility.

ThemainMethod
Notethatyoucancallstaticmethodswithouthavinganyobjects.Forexample,youneverconstructanyobjectsoftheMathclasstocallMath.pow.

Forthesamereason,themainmethodisastaticmethod.

publicclassApplication
{
publicstaticvoidmain(String[]args)
{
//constructobjectshere
...
}
}

Themainmethoddoesnotoperateonanyobjects.Infact,whenaprogramstarts,therearentanyobjectsyet.Thestaticmainmethodexecutes,andconstructstheobjectsthattheprogramneeds.


Everyclasscanhaveamainmethod.Thatisahandytrickforunittestingofclasses.Forexample,youcanaddamainmethodtotheEmployeeclass:

classEmployee
{
publicEmployee(Stringn,doubles,
intyear,intmonth,intday)
{
name=n;
salary=s;
GregorianCalendarcalendar
=newGregorianCalendar(year,month-1,day);
hireDay=calendar.getTime();
}
...
publicstaticvoidmain(String[]args)//unittest
{
Employeee=newEmployee("Romeo",50000);
e.raiseSalary(10);
System.out.println(e.getName()+""+e.getSalary());
}
...
}

IfyouwanttotesttheEmployeeclassinisolation,yousimplyexecute

javaEmployee

Iftheemployeeclassisapartofalargerapplication,thenyoustarttheapplicationwith

javaApplication

andthemainmethodoftheEmployeeclassisneverexecuted.



TheprograminExample4-3containsasimpleversionoftheEmployeeclasswithastaticfieldnextIdandastaticmethodgetNextId.WefillanarraywiththreeEmployeeobjectsandthenprinttheemployeeinformation.Finally,weprintthenumberofidentificationnumbersassigned.

NotethattheEmployeeclassalsohasastaticmainmethodforunittesting.Tryrunningboth

javaEmployee

and

javaStaticTest

toexecutebothmainmethods.

Example4-3StaticTest.java
1.publicclassStaticTest
2.{
3.publicstaticvoidmain(String[]args)
4.{
5.//fillthestaffarraywiththreeEmployeeobjects
6.Employee[]staff=newEmployee[3];
7.
8.staff[0]=newEmployee("Tom",40000);
9.staff[1]=newEmployee("Dick",60000);
10.staff[2]=newEmployee("Harry",65000);
11.
12.//printoutinformationaboutallEmployeeobjects
13.for(inti=0;i<staff.length;i++)
14.{
15.Employeee=staff[i];
16.e.setId();
17.System.out.println("name="+e.getName()
18.+",id="+e.getId()
19.+",salary="+e.getSalary());
20.}
21.
22.intn=Employee.getNextId();//callsstaticmethod
23.System.out.println("Nextavailableid="+n);
24.}
25.}
26.
27.classEmployee
28.{
29.publicEmployee(Stringn,doubles)
30.{
31.name=n;
32.salary=s;
33.id=0;
34.}
35.
36.publicStringgetName()
37.{
38.returnname;
39.}
40.
41.publicdoublegetSalary()
42.{
43.returnsalary;
44.}
45.
46.publicintgetId()
47.{
48.returnid;
49.}
50.
51.publicvoidsetId()
52.{
53.id=nextId;//setidtonextavailableid
54.nextId++;
55.}
56.
57.publicstaticintgetNextId()
58.{
59.returnnextId;//returnsstaticfield
60.}
61.
62.publicstaticvoidmain(String[]args)//unittest
63.{
64.Employeee=newEmployee("Harry",50000);
65.System.out.println(e.getName()+""+e.getSalary());
66.}
67.
68.privateStringname;
69.privatedoublesalary;
70.privateintid;
71.privatestaticintnextId=1;
72.}


那这个对象有什么意义?现在很多用javabean的人就不能保证对象有完整的意义,不成熟的使用模式等导致代码疯狂增长,调试维护的时间要得多得多。在说性能之前,先说说你这个比较的来历。据说微软为了证明。net比java好。
透明 该用户已被删除
沙发
 楼主| 发表于 2015-2-26 22:01:23 | 显示全部楼层
象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-5-31 04:57

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表