仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1152|回复: 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-1-21 13:04:10 | 只看该作者
你可以去承接一些项目做了,一开始可能有些困难,可是你有技术积累,又考虑周全,接下项目来可以迅速作完,相信大家以后都会来找你的,所以Money就哗啦啦的。。。。。。
莫相离 该用户已被删除
板凳
发表于 2015-1-25 19:42:21 | 只看该作者
如果你学过HTML,那么事情要好办的多,如果没有,那你快去补一补HTML基础吧。其实JSP中的Java语法也不多,它更象一个脚本语言,有点象ASP。
兰色精灵 该用户已被删除
地板
发表于 2015-2-3 17:54:57 | 只看该作者
你一定会高兴地说,哈哈,原来成为Java高手就这么简单啊!记得Tomjava也曾碰到过一个项目经理,号称Java很简单,只要三个月就可以学会。
精灵巫婆 该用户已被删除
5#
发表于 2015-2-5 21:36:36 | 只看该作者
Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站
飘灵儿 该用户已被删除
6#
发表于 2015-2-6 22:07:01 | 只看该作者
如果要向java web方向发展也要吧看看《Java web从入门到精通》学完再到《Struts2.0入门到精通》这样你差不多就把代码给学完了。有兴趣可以看一些设计模块和框架的包等等。
愤怒的大鸟 该用户已被删除
7#
发表于 2015-2-10 04:20:29 | 只看该作者
你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?
第二个灵魂 该用户已被删除
8#
发表于 2015-2-19 07:42:03 | 只看该作者
Java是一个纯的面向对象的程序设计语言,它继承了 C++语言面向对象技术的核心。Java舍弃了C ++语言中容易引起错误的指针(以引用取代)、运算符重载(operator overloading)
灵魂腐蚀 该用户已被删除
9#
发表于 2015-2-25 21:29:20 | 只看该作者
《JAVA语言程序设计》或《JAVA从入门到精通》这两本书开始学,等你编程有感觉的时候也可以回看一下。《JAVA读书笔记》这本书,因为讲的代码很多,也很容易看懂,涉及到面也到位。是你学习技术巩固的好书,学完后就看看《JAVA编程思想》这本书,找找一个自己写的代码跟书上的代码有什么不一样。
透明 该用户已被删除
10#
 楼主| 发表于 2015-2-26 22:01:23 | 只看该作者
象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。
不帅 该用户已被删除
11#
发表于 2015-3-8 18:12:22 | 只看该作者
是一种使网页(Web Page)由静态(Static)转变为动态(Dynamic)的语言
爱飞 该用户已被删除
12#
发表于 2015-3-11 12:09:24 | 只看该作者
是一种使网页(Web Page)产生生动活泼画面的语言
若相依 该用户已被删除
13#
发表于 2015-3-12 05:38:46 | 只看该作者
是一种简化的C++语言 是一种安全的语言,具有阻绝计算机病毒传输的功能
老尸 该用户已被删除
14#
发表于 2015-3-17 19:08:42 | 只看该作者
是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言
深爱那片海 该用户已被删除
15#
发表于 2015-3-24 20:02:40 | 只看该作者
Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站
谁可相欹 该用户已被删除
16#
发表于 2015-3-31 12:45:24 | 只看该作者
让你能够真正掌握接口或抽象类的应用,从而在原来的Java语言基础上跃进一步,更重要的是,设计模式反复向你强调一个宗旨:要让你的程序尽可能的可重用。
金色的骷髅 该用户已被删除
17#
发表于 2015-3-31 17:55:13 | 只看该作者
是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言
因胸联盟 该用户已被删除
18#
发表于 2015-4-3 01:19:16 | 只看该作者
关于设计模式的资料,还是向大家推荐banq的网站 [url]http://www.jdon.com/[/url],他把GOF的23种模式以通俗易懂的方式诠释出来,纯Java描述,真是经典中的经典。
山那边是海 该用户已被删除
19#
发表于 2015-4-15 18:50:30 | 只看该作者
你一定会高兴地说,哈哈,原来成为Java高手就这么简单啊!记得Tomjava也曾碰到过一个项目经理,号称Java很简单,只要三个月就可以学会。
海妖 该用户已被删除
20#
发表于 2015-4-19 09:52:11 | 只看该作者
《JAVA语言程序设计》或《JAVA从入门到精通》这两本书开始学,等你编程有感觉的时候也可以回看一下。《JAVA读书笔记》这本书,因为讲的代码很多,也很容易看懂,涉及到面也到位。是你学习技术巩固的好书,学完后就看看《JAVA编程思想》这本书,找找一个自己写的代码跟书上的代码有什么不一样。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2024-5-15 01:09

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

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