Design with static members (轉)
Advertisement: Support World, click here!
March 1999HOMEFEATURED TUTORIALLUMNSNEWS & REVIEWORUMJW RESABOUT JW
ARCHIVE
TOPICAL INDEX
Core Java
Enterprise Java
Micro Java
Applied Java
Java Community
JAVA Q&A INDEX
JAVA 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 outs of s, fit in a design that's object-oriented. (1,500 s)
By Bill Venners
Printer-friendly version | 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 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
An complete online reprint of Chapter 7, "The Linking Model," of Bill Venners' book Inside the Java Virtual Machine
The handout and slides for Bill Venners' Dynamic Extension in Java talk.
Bill Venners recently returned from his European bike trip. Read about it at:
The discussion forum devoted to the material presented in this article
Links to all previous design techniques articles
Recommended books on Java design
A transcript of an debate between Bill Venners, Mark Johnson (JavaWorld's JavaBeans columnist), and Mark Balbe on whether or not all objects should be made into beans
Object orientation FAQ
7237 Links on Object Orientation
The Object-Oriented Page
Collection of information on OO approach
Design Patterns Home Page
/patterns/patterns.html">
A Comparison of and OOD Methods
Object-Oriented Analysis and Design Methods: A Comparative Review
Patterns discussion FAQ
Patterns in Java AWT
Software Technology's Design Patterns Page
Previous Design Techniques articles
Advertisement: Support JavaWorld, click here!
HOME | FEATURED TUTORIALS | COLUMNS | NEWS & REVIEWS | FORUM | JW RESOURCES | ABOUT JW | FEEaCK
Copyright ? JavaWorld.com, an IDG company
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-996809/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- sonar程式碼質量檢測告警“static“ base class members should not be accessed via derived types
- 解析static!(轉)
- 理解static(轉)
- Viewing Password File Members (49)View
- Accessing Internal Members in the UNO FrameworkFramework
- 【轉】C++ static關鍵字C++
- Observer Design Pattern in C#! (轉)ServerC#
- C++中型別轉換static_castC++型別AST
- static
- [轉] Incomplete List of Mistakes in the Design of CSSCSS
- 設計模式(Design Patterns)筆記 (轉)設計模式筆記
- c++ static_cast顯式型別轉換C++AST型別
- java static 與 static靜態程式碼塊Java
- C語言中的 static變數、static函式C語言變數函式
- 【24】若所有引數皆需型別轉換,請為此採用non-members函式型別函式
- Swift代理報錯Optional can only be applied to members of an @objc protocolSwiftAPPOBJProtocol
- [Cexpert-002] How to assign default values to fields/members of a struct?Struct
- Design Patterns: Solidify Your C# Application Architecture with Design Patterns中文版(中篇) (轉)SolidC#APP
- Design Patterns: Solidify Your C# Application Architecture with Design Patterns中文版(下篇) (轉)SolidC#APP
- php static dynamicPHP
- C#staticC#
- Java之StaticJava
- static變數變數
- Interface中加Static
- Java中static、final、static final的區別Java
- 飛槳Paddle動轉靜@to_static技術設計
- Design Patterns: Solidify Your C# Application Architecture with Design Patterns中文版(尾篇二) (轉)SolidC#APP
- Design Patterns: Solidify Your C# Application Architecture with Design Patterns中文版(尾篇一) (轉)SolidC#APP
- java中的Static、final、Static final各種用法Java
- PHP中的staticPHP
- 理解C++ staticC++
- oop_promax_staticOOP
- static關鍵字
- Design Systems 02 - 什麼是 Design Principles
- ORA-00313 open failed for members of log group解決辦法AI
- PHP類的靜態(static)方法和靜態(static)變數PHP變數
- Material DesignMaterial Design
- design for failureAI