JAVA网页设计JAVA静态变量
在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;
7.
8.staff=newEmployee("Tom",40000);
9.staff=newEmployee("Dick",60000);
10.staff=newEmployee("Harry",65000);
11.
12.//printoutinformationaboutallEmployeeobjects
13.for(inti=0;i<staff.length;i++)
14.{
15.Employeee=staff;
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好。 你可以去承接一些项目做了,一开始可能有些困难,可是你有技术积累,又考虑周全,接下项目来可以迅速作完,相信大家以后都会来找你的,所以Money就哗啦啦的。。。。。。 如果你学过HTML,那么事情要好办的多,如果没有,那你快去补一补HTML基础吧。其实JSP中的Java语法也不多,它更象一个脚本语言,有点象ASP。 你一定会高兴地说,哈哈,原来成为Java高手就这么简单啊!记得Tomjava也曾碰到过一个项目经理,号称Java很简单,只要三个月就可以学会。 Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站 如果要向java web方向发展也要吧看看《Java web从入门到精通》学完再到《Struts2.0入门到精通》这样你差不多就把代码给学完了。有兴趣可以看一些设计模块和框架的包等等。 你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢? Java是一个纯的面向对象的程序设计语言,它继承了 C++语言面向对象技术的核心。Java舍弃了C ++语言中容易引起错误的指针(以引用取代)、运算符重载(operator overloading) 《JAVA语言程序设计》或《JAVA从入门到精通》这两本书开始学,等你编程有感觉的时候也可以回看一下。《JAVA读书笔记》这本书,因为讲的代码很多,也很容易看懂,涉及到面也到位。是你学习技术巩固的好书,学完后就看看《JAVA编程思想》这本书,找找一个自己写的代码跟书上的代码有什么不一样。 象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。 是一种使网页(Web Page)由静态(Static)转变为动态(Dynamic)的语言 是一种使网页(Web Page)产生生动活泼画面的语言 是一种简化的C++语言 是一种安全的语言,具有阻绝计算机病毒传输的功能 是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言 Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站 让你能够真正掌握接口或抽象类的应用,从而在原来的Java语言基础上跃进一步,更重要的是,设计模式反复向你强调一个宗旨:要让你的程序尽可能的可重用。 是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言 关于设计模式的资料,还是向大家推荐banq的网站 http://www.jdon.com/,他把GOF的23种模式以通俗易懂的方式诠释出来,纯Java描述,真是经典中的经典。 你一定会高兴地说,哈哈,原来成为Java高手就这么简单啊!记得Tomjava也曾碰到过一个项目经理,号称Java很简单,只要三个月就可以学会。 《JAVA语言程序设计》或《JAVA从入门到精通》这两本书开始学,等你编程有感觉的时候也可以回看一下。《JAVA读书笔记》这本书,因为讲的代码很多,也很容易看懂,涉及到面也到位。是你学习技术巩固的好书,学完后就看看《JAVA编程思想》这本书,找找一个自己写的代码跟书上的代码有什么不一样。
页:
[1]