分享
 
 
 

Design with static members

王朝vc·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

Advertisement: Support JavaWorld, click here!

March 1999HOMEFEATURED TUTORIALSCOLUMNSNEWS & REVIEWSFORUMJW RESOURCESABOUT JW

ARCHIVE

TOPICAL INDEX

Core Java

Enterprise Java

Micro Java

Applied Java

Java Community

JAVA Q&A INDEX

JAVA TIPS INDEX

JavaWorld Services

Free JavaWorld newsletters

ProductFinder

Education Resources

White Paper Library

NEW! Rational Resources

Design Techniques

Design with static members

How to put static fields and methods to work

Summary

In this installment of his Design Techniques column, Bill Venners discusses the ways in which static fields and methods, which exist outside of objects, fit in a design that's object-oriented. (1,500 words)

By Bill Venners

Printer-friendly version | Mail this to a friend

Page 1 of 2

Advertisement

lthough Java is object-oriented to a great extent, it is not a pure object-oriented language. One of the reasons Java is not purely object-oriented is that not everything in it is an object. For example, Java allows you to declare variables of primitive types (int, float, boolean, etc.) that aren't objects. And Java has static fields and methods, which are independent and separate from objects. This article gives advice on how to use static fields and methods in a Java program, while maintaining an object-oriented focus in your designs.

The lifetime of a class in a Java virtual machine (JVM) has many similarities to the lifetime of an object. Just as an object can have state, represented by the values of its instance variables, a class can have state, represented by the values of its class variables. Just as the JVM sets instance variables to default initial values before executing initialization code, the JVM sets class variables to default initial values before executing initialization code. And like objects, classes can be garbage collected if they are no longer referenced by the running application.

Nevertheless, significant differences exist between classes and objects. Perhaps the most important difference is the way in which instance and class methods are invoked: instance methods are (for the most part) dynamically bound, but class methods are statically bound. (In three special cases, instance methods are not dynamically bound: invocation of private instance methods, invocation of init methods (constructors), and invocations with the super keyword. See Resources for more information.)

Another difference between classes and objects is the degree of data hiding granted by the private access levels. If an instance variable is declared private, only instance methods can access it. This enables you to ensure the integrity of the instance data and make objects thread-safe. The rest of the program cannot access those instance variables directly, but must go through the instance methods to manipulate the instance variables. In an effort to make a class behave like a well-designed object, you can make class variables private and define class methods that manipulate them. Nevertheless, you don't get as good a guarantee of thread safety or even data integrity in this way, because a certain kind of code has a special privilege that gives them direct access to private class variables: instance methods, and even initializers of instance variables, can access those private class variables directly.

So the static fields and methods of classes, although similar in many ways to the instance fields and methods of objects, have significant differences that should affect the way you use them in designs.

Treating classes as objects

As you design Java programs, you will likely encounter many situations in which you feel the need for an object that acts in some ways like a class. You may, for example, want an object whose lifetime matches that of a class. Or you may want an object that, like a class, restricts itself to a single instance in a given name space.

In design situations such as these, it can be tempting to create a class and use it like an object in order to define class variables, make them private, and define some public class methods that manipulate the class variables. Like an object, such a class has state. Like a well-designed object, the variables that define the state are private, and the outside world can only affect this state by invoking the class methods.

Unfortunately, some problems exist with this "class-as-object" approach. Because class methods are statically bound, your class-as-object won't enjoy the flexibility benefits of polymorphism and upcasting. (For definitions of polymorphism and dynamic binding, see the Design Techniques article, Composition versus Inheritance.) Polymorphism is made possible, and upcasting useful, by dynamic binding, but class methods aren't dynamically bound. If someone subclasses your class-as-object, they will not be able to override your class methods by declaring class methods of the same name; they will only be able to hide them. When one of these redefined class methods is invoked, the JVM will select the method implementation to execute not by the class of an object at runtime, but by the type of a variable at compile time.

In addition, the thread safety and data integrity achieved by your meticulous implementation of the class methods in your class-as-object is like a house built of straw. Your thread safety and data integrity will be guaranteed so long as everyone uses the class methods to manipulate the state stored in the class variables. But a careless or clueless programmer could, with the addition of one instance method that accesses your private class variables directly, inadvertently huff and puff and blow your thread safety and data integrity away.

For this reason, my main guideline concerning class variables and class methods is:

Don't treat classes like objects.

In other words, don't design with static fields and methods of a class as if they were the instance fields and methods of an object.

If you want some state and behavior whose lifetime matches that of a class, avoid using class variables and class methods to simulate an object. Instead, create an actual object and use a class variable to hold a reference to it and class methods to provide access to the object reference. If you want to ensure that only one instance of some state and behavior exists in a single name space, don't try to design a class that simulates an object. Instead, create a singleton -- an object guaranteed to have only one instance per name space.

Next page >

Page 1 Design with static members

Page 2 So what are class members good for?

Printer-friendly version | Mail this to a friend

Resources

Bill Venners' next book is Flexible Java

http://www.artima.com/flexiblejava/index.html

An complete online reprint of Chapter 7, "The Linking Model," of Bill Venners' book Inside the Java Virtual Machine

http://www.artima.com/insidejvm/linkmod.html

The handout and slides for Bill Venners' Dynamic Extension in Java talk.

http://www.artima.com/javaseminars/modules/DynaExt/index.html

Bill Venners recently returned from his European bike trip. Read about it at:

http://www.artima.com/bv/travel/bike98/index.html

The discussion forum devoted to the material presented in this article

http://www.artima.com/flexiblejava/fjf/classes/index.html

Links to all previous design techniques articles

http://www.artima.com/designtechniques/index.html

Recommended books on Java design

http://www.artima.com/designtechniques/booklist.html

A transcript of an e-mail debate between Bill Venners, Mark Johnson (JavaWorld's JavaBeans columnist), and Mark Balbe on whether or not all objects should be made into beans

http://www.artima.com/flexiblejava/comments/beandebate.html

Object orientation FAQ

http://www.cyberdyne-object-sys.com/oofaq/

7237 Links on Object Orientation

http://www.rhein-neckar.de/~cetus/software.html

The Object-Oriented Page

http://www.well.com/user/ritchie/oo.html

Collection of information on OO approach

http://arkhp1.kek.jp:80/managers/computing/activities/OO_CollectInfor/OO_CollectInfo.html

Design Patterns Home Page

http://hillside.net/patterns/patterns.html

A Comparison of OOA and OOD Methods

http://www.iconcomp.com/papers/comp/comp_1.html

Object-Oriented Analysis and Design Methods: A Comparative Review

http://wwwis.cs.utwente.nl:8080/dmrg/OODOC/oodoc/oo.html

Patterns discussion FAQ

http://gee.cs.oswego.edu/dl/pd-FAQ/pd-FAQ.html

Patterns in Java AWT

http://mordor.cs.hut.fi/tik-76.278/group6/awtpat.html

Software Technology's Design Patterns Page

http://www.sw-technologies.com/dpattern/

Previous Design Techniques articles

http://www.javaworld.com/topicalindex/jw-ti-techniques.html

Advertisement: Support JavaWorld, click here!

HOME | FEATURED TUTORIALS | COLUMNS | NEWS & REVIEWS | FORUM | JW RESOURCES | ABOUT JW | FEEDBACK

Copyright ?2003 JavaWorld.com, an IDG company

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有