Lang Environ

download Lang Environ

of 98

Transcript of Lang Environ

  • 7/29/2019 Lang Environ

    1/98

    TheJava LanguageEnvironment A WhitePaper

    May 1996

    JamesGosling

    Henry McGilton

    JavaSoft2550 Garcia AvenueMountain View, CA 94043 U.S.A408-343-1400

  • 7/29/2019 Lang Environ

    2/98

    PleaseRecycle

    Copyright Information

    1995, 1996, 1997 Sun Microsyste ms , Inc. All rights r eserv ed.

    2550 Garcia Avenue, Mountain View, California 94043-1100 U.S.A.This document at is protected by copyright. No part of this docum ent may be reprod uced in any form by any means with outpr ior written au thorization of Sun and its licensors, if any.

    The information described in this docum ent may be prot ected by one or more U.S. patents, foreign paten ts, or pendingapplications.

    TRADEMARKSSun, the Sun logo, Sun Microsystems, Solaris, HotJava, and Java are tradem arks or registered tr adem arks of SunMicrosystems, Inc. in the U.S. and certain other coun tries. The Du ke character is a trad emar k of Sun Microsystems, Inc., andCop yrigh t (c) 1992-1995 Sun Microsystem s, Inc. All Rights Reserved . UN IX is a register ed tra dem ark in the United States an dother coun tries, exclusively licensed throu gh X/ Op en Comp any, Ltd. OPEN LOOK is a registered tr adem ark of Novell, Inc.All other prod uct names men tioned herein are the trad emar ks of their respective own ers.

    X Window System is a tradem ark of the XConsor tium .

    THIS DOCU MENT IS PROVIDED AS IS WITHOU T WARRAN TY OF ANY KIND, EITHER EXPRESS OR IMPLIED,INCLUDIN G, BUT NO T LIMITED TO, THE IMPLIED WARRAN TIES OF MERCHAN TABILITY, FITNESS FOR APARTICULAR PURPOSE, OR NON-INFRINGEMENT.

    THIS DOCUMENT COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES AREPERIODICALLY ADDED TO THE IN FORMATION HEREIN; THESE CHA NGES WILL BE INCO RPORATED IN NEWEDITIONS OF TH E DOCUM ENT. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND / OR CH AN GES INTHE PROD UCT(S) AND/ O R THE PROGRAM(S) DESCRIBED IN THIS DOCUM ENT AT ANY TIME.

  • 7/29/2019 Lang Environ

    3/98

    iv

    Contents

    1. Introduction to Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

    1.1 Beginnings of the Java Langu age Project. . . . . . . . . . . . . . 12

    1.2 Design Goals of Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    1.2.1 Simp le, Object Oriented, and Familiar . . . . . . . . . . . 131.2.2 Robust and Secure. . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    1.2.3 Architecture Neutral and Portable . . . . . . . . . . . . . . 14

    1.2.4 High Per forman ce . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    1.2.5 Interpreted, Threaded, and Dynamic . . . . . . . . . . . . 15

    1.3 The Java Platforma New App roach to DistributedCom puting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    2. JavaSimple and Familiar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

    2.1 Main Features of the Java Langu age . . . . . . . . . . . . . . . . . 20

    2.1.1 Primitive Data Typ es . . . . . . . . . . . . . . . . . . . . . . . . . 20

    2.1.2 Arithmetic and Relational Operators . . . . . . . . . . . . 21

    2.1.3 Arr ays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    2.1.4 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

  • 7/29/2019 Lang Environ

    4/98

    v The Java Language Environment May 1996

    2.1.5 Mu lti-Level Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    2.1.6 Memory Management and Garbage Collection . . . 24

    2.1.7 The Backgroun d Garbage Collector . . . . . . . . . . . . . 25

    2.1.8 Integrated Thread Synchronization . . . . . . . . . . . . . 25

    2.2 Features Removed from C and C++. . . . . . . . . . . . . . . . . . 26

    2.2.1 No More Typed efs, Defines, or Preprocessor . . . . . 26

    2.2.2 No More Stru ctures or Unions . . . . . . . . . . . . . . . . . 27

    2.2.3 No Enum s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    2.2.4 No More Fun ctions . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    2.2.5 No More Multiple Inh eritance. . . . . . . . . . . . . . . . . . 29

    2.2.6 No More Goto Statem ents . . . . . . . . . . . . . . . . . . . . . 30

    2.2.7 No More Operator Overloading . . . . . . . . . . . . . . . . 30

    2.2.8 No More Autom atic Coercions . . . . . . . . . . . . . . . . . 30

    2.2.9 No More Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

    2.3 Summa ry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

    3. Java is Object Oriented . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    3.1 Object Techn ology in Java . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    3.2 Wha t Are Objects? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    3.3 Basics of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    3.3.1 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    3.3.2 Instantiating an Object from its Class . . . . . . . . . . . . 35

    3.3.3 Constru ctors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    3.3.4 Method s and Messaging . . . . . . . . . . . . . . . . . . . . . . 38

    3.3.5 Finalizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

    http://-/?-http://-/?-
  • 7/29/2019 Lang Environ

    5/98

    Contents vi

    3.3.6 Subclasses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

    3.3.7 Java Langu age Interfaces . . . . . . . . . . . . . . . . . . . . . . 43

    3.3.8 Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

    3.3.9 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

    3.3.10 Class Variables and Class Method s. . . . . . . . . . . . . . 46

    3.3.11 Abstract Method s . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

    3.4 Summa ry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

    4. Architecture Neutral, Portable, and Robust . . . . . . . . . . . . . . . 50

    4.1 Architecture Neu tral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

    4.1.1 Byte Cod es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

    4.2 Port able . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    4.3 Robust . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

    4.3.1 Strict Comp ile-Time and Run-Time Checking . . . . . 53

    4.4 Summa ry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

    5. Interpreted and Dynamic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    5.1 Dynam ic Loading an d Bind ing. . . . . . . . . . . . . . . . . . . . . . 57

    5.1.1 The Fragile Superclass Problem . . . . . . . . . . . . . . . . 57

    5.1.2 Solving the Fragile Sup erclass Problem . . . . . . . . . . 58

    5.1.3 Run-Time Representations . . . . . . . . . . . . . . . . . . . . . 58

    5.2 Summa ry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

    6. Security in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

    6.1 Memor y Allocation and Layou t . . . . . . . . . . . . . . . . . . . . . 60

    6.2 Security Checks in the Class Loader . . . . . . . . . . . . . . . . . 61

    6.3 The Byte Code Verification Process . . . . . . . . . . . . . . . . . . 61

    http://-/?-http://-/?-
  • 7/29/2019 Lang Environ

    6/98

    vii The Java Language Environment May 1996

    6.3.1 The Byte Cod e Verifier . . . . . . . . . . . . . . . . . . . . . . . . 63

    6.4 Security in the Java Netw orking Package . . . . . . . . . . . . . 64

    6.5 Summa ry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

    7. Multithreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

    7.1 Thread s at the Java Langu age Level . . . . . . . . . . . . . . . . . 66

    7.2 Integrated Threa d Synchronization . . . . . . . . . . . . . . . . . . 67

    7.3 Multithread ing Sup por tConclusion . . . . . . . . . . . . . . . . 68

    8. Performance and Comparisons. . . . . . . . . . . . . . . . . . . . . . . . . . 70

    8.1 Perfor ma nce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    8.2 The Java Langu age Comp ared . . . . . . . . . . . . . . . . . . . . . . 71

    8.3 A Major Benefit of Java: Fast and Fearless Prototyping. . 74

    8.4 Summa ry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

    9. Java Base System and Libraries . . . . . . . . . . . . . . . . . . . . . . . . . 76

    9.1 Java Langu age Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

    9.2 Inpu t Outp ut Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

    9.3 Utility Packag e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

    9.4 Abstract Wind ow Toolkit. . . . . . . . . . . . . . . . . . . . . . . . . . . 79

    10. The HotJava World-Wide Web Browser . . . . . . . . . . . . . . . . . . 82

    10.1 The Evolution of Cyberspa ce . . . . . . . . . . . . . . . . . . . . . . . 83

    10.1.1 First Generation Browsers . . . . . . . . . . . . . . . . . . . . . 84

    10.1.2 The HotJava Brow serA New Concep t in Web Brow sers85

    10.1.3 The Essential Difference . . . . . . . . . . . . . . . . . . . . . . . 85

    10.1.4 Dynam ic Conten t . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

    http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-
  • 7/29/2019 Lang Environ

    7/98

    Contents viii

    10.1.5 Dyn am ic Typ es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

    10.1.6 Dynam ic Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

    10.2 Freedom to Inn ovate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

    10.3 Imp lementation D etails . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

    10.4 Secu rity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

    10.4.1 The First Layerthe Java Language Interpreter. . . 92

    10.4.2 The Next Layerthe Higher Level Protocols . . . . . 92

    10.5 HotJavathe Promise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

    11. Further Reading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

    http://-/?-http://-/?-
  • 7/29/2019 Lang Environ

    8/98

    ix The Java Language Environment May 1996

  • 7/29/2019 Lang Environ

    9/98

    10

    Introduction toJava 1

    The Next Stage of the Known,Or a Comp letely New Paradigm?

    Taiichi Sakaiya The Knowledge-Value Revolution

    The Softw are Developers Burden

    Imagine youre a software ap plication d eveloper. Your program ming lang uage

    of choice (or the lan gu age th ats been foisted on yo u) is C or C++. You ve beenat this for quite a w hile and your job d oesnt seem to be getting a ny easier.These past few years youve seen the growth of multiple incompatiblehardware architectures, each supporting multiple incompatible operatingsystems, with each platform operating with one or more incompatiblegrap hical user interfaces. Now youre sup posed to cope with all this and m akeyour applications work in a distributed client-server environment. The growthof the Internet, th e World-Wide Web, and electronic commerce haveintroduced new dimensions of complexity into the development process.

  • 7/29/2019 Lang Environ

    10/98

    11 The JavaLanguage Environment M ay 1996

    1

    The tools you use to d evelop ap plications d ont seem to h elp you mu ch. Yourestill coping w ith the sam e old p roblems; the fashionable new ob ject-orientedtechniques seem to have added new problems without solving the old ones.You say to you rself and your friend s, There has to be a better way!

    The Bett er Way is Here Now

    Now there is a better wa yits the Java programming language platform(Java for short) from Sun Microsystems. Imagine, if you will, thisdevelopment world Your p rogramm ing language is object oriented, yet its still dead simple.

    Your developm ent cycle is mu ch faster because Java is interpreted . Thecompile-link-load-test-crash-debug cycle is obsoletenow you just compileand run.

    Your applications are portable across multiple platforms. Write you rapplications once, and you never need to port themthey will run withoutmodification on multiple operating systems and hardware architectures.

    Your applications are robust because the Java run-time system managesmemory for you.

    Your interactive gra ph ical app lications hav e high performance becausemu ltiple concurrent thread s of activity in your app lication are sup ported byth e multithreading built into the Java language and runtime platform.

    Your applications are adaptable to changing environments because you candyn amically dow nload code modu les from anyw here on the network.

    Your end users can trust that you r app lications are secure , even thoughtheyre downloading code from all over the Internet; the Java run-timesystem has built-in protection against viruses and tampering.

    You don t need to d ream a bout these features. Theyre here now. The JavaProgramming Language p latform provides a portable , interpreted , high-

    performance , simple , object-oriented programming language and supporting run-time environment. This introductory chapter provides you with a brief look atthe main d esign goals of the Java system; the remainder of this pap er examinesthe features of Java in more d etail.

  • 7/29/2019 Lang Environ

    11/98

    Int roduction to Java 12

    1

    The last chapter of this paper describes the HotJava Browser (HotJava forshort). HotJava is an innovative World-Wide Web browser, and the first majorapp lications wr itten using th e Java p latform. H otJava is the first browser todyn amically dow nload an d execute Java code fragm ents from anyw here on theInternet, and can do so in a secure manner.

    1.1 Beginnings of the Java Language Project Java is designed to meet the challenges of application development in thecontext of heterogeneous, network-wide distributed environments. Paramountamong these challenges is secure delivery of applications that consume the

    minimum of system resources, can ru n on any hard ware and softwareplatform, and can be extended dynamically.

    Java originated as par t of a research p roject to develop ad vanced software for awide variety of network devices and embedd ed systems. The goal was todevelop a sma ll, reliable, portable, distributed, real-time op erating p latform.When th e project started, C++ w as the langu age of choice. But ov er time thedifficulties encoun tered w ith C++ grew to the p oint wh ere the problems couldbest be addressed by creating an entirely new language platform. Design and

    architecture d ecisions drew from a v ariety of languages su ch as Eiffel,SmallTalk, Objective C, an d Cedar/ M esa. The result is a lang uage platformthat has proven ideal for developing secure, distributed, network-based end-user applications in environments ranging from network-embedded devices tothe World-Wide Web and the desktop.

    1.2 Design Goals of Java

    The design requirements of Java are driven by the nature of the computingenvironments in w hich software must be deployed.

    The massive growth of the Internet and the World-Wide Web leads us to acompletely new way of looking at development and distribution of software.To live in the w orld of electronic comm erce and distribution, Java m ust en ablethe development of secure, high performance, and h ighly robust applications onmult iple platforms in heterogeneous , distributed networks .

  • 7/29/2019 Lang Environ

    12/98

    13 The JavaLanguage Environment M ay 1996

    1

    Operating on multiple platforms in heterogeneous networks invalidates thetraditional schemes of binary distribution, release, upgrade, patch, and so on.To sur vive in this jungle, Java m ust be architectu re n eutral , portable , anddynamically adaptable .

    The Java system that emerged to meet these needs is simple , so it can be easilyprogrammed by most developers; familiar , so that current d evelopers can easilylearn Java; object oriented , to take advantage of mod ern software d evelopmentmethod ologies and to fit into d istributed client-server ap plications;multithreaded , for high performance in applications that need to performmu ltiple concurrent activities, such as mu ltimed ia; and interpreted , formaximum portability and dynamic capabilities.

    Together, the above requ irements comp rise quite a collection of bu zzw ords, solets examine som e of them and their respective benefits before going on .

    1.2.1 Simple, Object Oriented, and Familiar

    Primary characteristics of Java include a simple language that can beprogrammed without extensive programmer training wh ile being attuned tocurrent software p ractices. The fun dam ental concepts of Java are gra spedquickly; programmers can be productive from the very beginning.

    Java is designed to be object orient ed from the ground up . Object technology hasfinally found its way into the programming mainstream after a gestationperiod of thirty years. The needs of distributed , client-server based systemscoincide w ith the encap sulated, m essage-passing p arad igms of object-basedsoftware. To fun ction w ithin increasingly comp lex, netw ork-basedenvironments, programming systems must adopt object-oriented concepts.Java p rovides a clean an d efficient object-based d evelopmen t platform.

    Programm ers u sing Java can access existing libraries of tested objects thatprovide functionality ranging from basic data types through I/ O and network interfaces to grap hical user interface toolkits. These libraries can be extendedto provide new behavior.

    Even though C++ was rejected as an implementation language, keeping Javalooking like C++ as far as possible results in Java being a familiar language,wh ile removing th e un necessary comp lexities of C++. Having Java retain manyof the object-oriented features an d the look and feel of C++ means thatprogrammers can migrate easily to Java and be productive quickly.

  • 7/29/2019 Lang Environ

    13/98

    Int roduction to Java 14

    1

    1.2.2 Robust and Secure

    Java is d esigned for creating highly reliable software. It provides extensive

    compile-time checking, followed by a second level of run-time checking.Language features gu ide p rogrammers toward s reliable programming habits.

    The mem ory m anagem ent m odel is extremely simp le: objects are created w itha new operator. There are no explicit programmer-defined pointer data types,no pointer arithmetic, and automatic garbage collection. This simple memorymanagement model eliminates entire classes of programming errors thatbedevil C and C++ prog ramm ers. You can d evelop Java langu age code withconfidence that the system will find many errors quickly and that major

    problems w ont lay dorman t un til after your p roduction code h as shipped.

    Java is designed to operate in distributed environments, which means thatsecurity is of paramount importance. With security features designed into thelanguage and run-time system, Java lets you construct applications that cantbe invaded from outside. In the network environment, applications written inJava are secure from intrusion by unauthorized code attempting to get behindthe scenes and create viruses or inv ade file systems.

    1.2.3 A rchitecture Neutral and Portable

    Java is designed to support applications that will be deployed intoheterogeneous network environments. In such environments, applicationsmu st be capable of executing on a variety of hard ware a rchitectures. Withinthis variety of hard w are platforms, applications mu st execute atop a variety of operating systems and interoperate with mu ltiple programming languageinterfaces. To accommod ate the d iversity of opera ting environm ents, the Java

    compiler generates bytecodes an architectu re neutral intermediate formatdesigned to transport code efficiently to multiple hardware and softwareplatforms. The interpreted nature of Java solves both the binary distributionproblem and the version problem; the same Java language byte codes will runon any p latform.

    Architecture n eutrality is just on e part of a truly portable system. Java takesportability a stage furth er by being strict in its definition of the ba sic langu age.Java p uts a stake in the grou nd and specifies the sizes of its basic data typ es

    and the behavior of its arithm etic operators. Your p rograms are th e same onevery platformthere are no data type incompatibilities across hardware andsoftware architectures.

  • 7/29/2019 Lang Environ

    14/98

    15 The JavaLanguage Environment M ay 1996

    1

    The architecture-neutral and portable language platform of Java is known asth e Java Virtual Machine . Its the specification of an abstract machine for whichJava lan guag e comp ilers can g enerate code. Specific imp lementations of theJava Virtual Machine for specific hardw are and software platforms th enprovid e the concrete realization of the v irtual m achine. The Java VirtualMachine is based prima rily on th e POSIX interface specificationan ind ustry-stand ard definition of a p ortable system interface. Imp lementing the JavaVirtual Machine on n ew architectures is a relatively straightforward task aslong as the target platform meets basic requirements such as support formultithreading.

    1.2.4 High PerformancePerformance is always a consideration. Java achieves sup erior performan ce byadopting a scheme by w hich the interpreter can run at full speed w ithoutneeding to check the run-time environmen t. The automatic garbage collector runsas a low-priority background thread, ensuring a high probability that memoryis available when required, leading to better performance. Applicationsrequiring large amounts of compu te pow er can be designed such thatcompu te-intensive sections can be rew ritten in native ma chine code as requ iredand interfaced with the Java platform. In general, users perceive thatinteractive applications respond quickly even though theyre interpreted.

    1.2.5 Interpreted, Threaded, and Dynamic

    The Java interpreter can execute Java bytecodes directly on a ny m achine towhich the interpreter and run-time system have been ported. In an interpretedplatform such as Java system, the link phase of a program is simple,

    incremen tal, and lightw eight. You ben efit from m uch faster d evelopmen tcyclesprototyping, experimentation, and rapid development are the normalcase, versus th e trad itional heav yw eight compile, link, an d test cycles.

    Modern netw ork-based ap plications, such as th e HotJava World-Wide Webbrowser, typically need to do several things at the same time. A user workingwith HotJava can run several animations concurrently while downloading animage an d scrolling the p age. Javas multithreading capability provides themeans to build applications with many concurrent threads of activity.

    Multithreading thus results in a high degree of interactivity for the end user.

  • 7/29/2019 Lang Environ

    15/98

    Int roduction to Java 16

    1

    Java sup ports mu ltithreading at the language level with the add ition of sophisticated synchronization primitives: the language library provides theThread class, and the run-time system provides monitor and condition lock primitives. At the library level, moreover, Javas high-level system librarieshave been w ritten to be thread safe : the functionality p rovided by the libraries isavailable without conflict to m ultiple concurrent th reads of execution.

    While the Java compiler is strict in its compile-time static checking, thelanguage and run-time system are dynamic in their linking stages. Classes arelinked only as needed. New code modules can be linked in on demand from avariety of sources, even from sources across a netw ork. In the case of theHotJava brow ser and similar app lications, interactive executable code can be

    loaded from anyw here, which enables transparent u pd ating of app lications.The result is on-line services that constantly evolve; they can remain innovativeand fresh, draw more customers, and spur the growth of electronic commerceon the Internet.

    1.3 The Java Platforma New Approach to Distributed ComputingTaken ind ividua lly, the characteristics discussed abov e can be foun d in a

    variety of software development platforms. Whats completely new is theman ner in which Java and its run-time system have combined them to prod ucea flexible and powerful programming system.

    Developing your applications using Java results in software that is portableacross multiple machine architectures, operating systems, and graphical userinterfaces, secure , and high performance . With Java, your job as a softwaredeveloper is much easieryou focus your full attention on the end goal of shipping innovative products on time, based on the solid foundation of Java.

    The bett er way to develop software is here, now, brought to you by the Javalanguage p latform.

  • 7/29/2019 Lang Environ

    16/98

    17 The JavaLanguage Environment M ay 1996

    1

  • 7/29/2019 Lang Environ

    17/98

    18

    Java Simpleand Familiar 2

    You k now youve achieved perfection in d esign,Not when you have nothing more to add,

    But w hen you have nothing more to take away.

    Antoine d e Saint Exup ery.

    In his science-fiction novel, The Rolling St ones , Robert A. Heinlein comm ents:

    Every technology goes through three stages: first a crudely simple and quite un satisfactory gadget; second, an enormously complicated group of gadgets designed to overcome t he shortcomings of the original and achieving thereby somewhat satisfactory performance through extremely

    complex compromise; third, a final proper design therefrom .Heinleins comment could well describe the evolution of many programminglanguages. Java presents a new viewpoint in the evolution of programminglanguag escreation of a small and simple lang uage thats still sufficientlycomprehen sive to add ress a wid e variety of software app lication d evelopmen t.Although Java is sup erficially similar to C an d C++, Java g ained its simplicityfrom the system atic remov al of features from its p redecessors. This chapterdiscusses two of the p rimary design features of Java, na mely, its simple (from

    removing features) and familiar (because it looks like C and C++). The next

  • 7/29/2019 Lang Environ

    18/98

    19 The JavaLanguage Environment M ay 1996

    2

    chapter discusses Javas object-oriented features in more detail. At the end of this chapter you ll find a discussion on features eliminated from C and C++ inthe evolu tion of Java.

    Des ign Go al s

    Simplicity is one of Javas overriding d esign goals. Simplicity an d removal of many features of dubious worth from its C and C++ ancestors keep Javarelatively small and reduce the programmers burden in producing reliableapp lications. To this end , Java d esign team examined man y aspects of themodern C and C++ languages * to determine features that could beeliminated in the context of modern object-oriented programming.

    Anoth er major design goal is that Java look familiar to a m ajority of programmers in the p ersonal compu ter and workstation arenas, where a largefraction of system programmers and application programmers are familiarwith C and C++. Thu s, Java looks like C++. Programmers familiar with C,Objective C, C++, Eiffel, Ad a, and related langu ages shou ld find their Javalanguage learning curve quite shorton the order of a couple of weeks.

    To illustrate the simp le and familiar asp ects of Java, w e follow the trad ition of

    a long line of illustrious program ming books by show ing you the HelloWorldprogram. Its about the simplest program you can write that actually doessomething. H eres HelloWorld implemented in Java.

    class HelloWorld {static public void main(String args[]) {

    System.out.println("Hello world!");}

    }

    This example declares a class named HelloWorld . Classes are discussed in thenext chapter on object-oriented programming, but in general we assume thereader is familiar w ith object technology an d un derstan ds th e basics of classes,objects, instance variables, and method s.

    Within th e HelloWorld class, we declare a single method called main() whichin turn contains a single method in vocation to d isplay the string "Hello world!"on the standard output. The statement that prints "Hello world!" does so by

    * Now enjoying their silver anniversaries

  • 7/29/2019 Lang Environ

    19/98

    JavaSimple and Familiar 20

    2

    invoking the println method of the out object. Th e out object is a classvariable in the System class that performs ou tpu t op erations on files. Thats allthere is to HelloWorld .

    2.1 M ain Features of the Java LanguageJava follows C++ to some d egree, which carries the ben efit of it being familiarto man y p rogramm ers. This section d escribes the essential features of Java an dpoints out where the language diverges from its ancestors C and C++.

    2.1.1 Primitive Data TypesOther than the primitive data types discussed here, everything in Java is anobject. Even the p rimitive data typ es can be encapsu lated inside library-supplied objects if required. The Java programming language follows C andC++ fairly closely in its set of basic data types, w ith a coup le of minorexceptions. There are only three group s of primitive data ty pes, nam ely,numeric types, character types, and Boolean types.

    Num eric Dat a Ty pes Integer nu meric types are 8-bit byte , 16-bit short , 32-bit int , and 64-bit long .The 8-bit byte data type in Java has replaced the old C and C++ char datatype. Java p laces a d ifferent interp retation on th e char data type, as discussedbelow.

    There is no unsigned type specifier for integer data types in Java.

    Real nu meric types are 32-bit float and 64-bit double . Real numeric types

    and their arithm etic operations are as d efined by th e IEEE 754 specification. Afloating p oint literal value, like 23.79 , is considered double by d efault; youmust explicitly cast it to float if you w ish to assign it to a float variable.

    Character Data Types

    Java langu age character data is a dep arture from tra ditional C. Javas char datatype defines a sixteen-bit Unicode character. Unicode chara cters are un signed16-bit valu es that define character codes in th e ran ge 0 throu gh 65,535. If you

    write a declaration such aschar myChar = Q;

    2

  • 7/29/2019 Lang Environ

    20/98

    21 The JavaLanguage Environment M ay 1996

    2

    you g et a Unicode (16-bit un signed valu e) type initialized to the Un icode v alueof the character Q. By ad opting th e Unicode character set stand ard for itscharacter data type, Java language applications are amenable to

    internationalization and localization, greatly expanding the market for world-wide applications.

    Boo lean Da t a Types

    Java ad ded a Boolean d ata typ e as a p rimitive type, tacitly ratifying existing Cand C++ programming practice, where developers define keywords for TRUEan d FALSE or YES an d NO or similar constru cts. A Java boolean variableassumes the value true or false . A Java boolean is a distinct data type;

    un like comm on C pra ctice, a Java boolean type cant be converted to anynum eric type.

    2.1.2 A rithmetic and Relational Operators

    All the familiar C and C++ operators apply. The Java programming languagehas no unsigned data typ es, so the >>> operator has been add ed to thelanguag e to ind icate an un signed (logical) right sh ift. Java also u ses the +

    operator for string concatenation; concatenation is covered below in th ediscussion on strings.

    2.1.3 A rrays

    In contrast to C and C++, Java language arrays are first-class language objects.An ar ray in Java is a real object with a ru n-time rep resenta tion. You can d eclareand allocate arrays of any typ e, and y ou can a llocate arrays of arrays to obtainmulti-dimensional arrays.

    You d eclare an ar ray of, say, Point s (a class youve declared elsewhere) with adeclaration like this:

    Point myPoints[];

    This code states that myPoints is an uninitialized array of Point s. At thistime, the only storage allocated for myPoints is a reference hand le. At somefuture time you must allocate the amount of storage you need, as in:

    myPoints = new Point[10];

    2

  • 7/29/2019 Lang Environ

    21/98

    JavaSimple and Familiar 22

    2

    to allocate an array of ten references to Point s that are initialized to the nu llreference. Notice that this allocation of an array doesnt actually allocate anyobjects of the Point class for you; you will have to also allocate the Point

    objects, something like this:int i;

    for (i = 0; i < 10; i++) {myPoints[i] = new Point();

    }

    Access to elements of myPoints can be performed via normal C-styleindexing, but a ll array accesses are checked to en sure that their indices are

    within the range of the array. An exception is generated if the ind ex is outsidethe bounds of the array.

    The length of an array is stored in the length instance variable of the specificarray: myPoints.length contains the number of elements in myPoints . Forinstance, the code fragm ent:

    howMany = myPoints.length;

    would assign the value 10 to the howMany variable.

    The C notion of a pointer to an ar ray of memory elemen ts is gone, and with it,the arbitrary pointer arithmetic that leads to unreliable code in C. No longercan you w alk off the end of an array, possibly trashing mem ory and leading tothe famous d elayed-crash synd rome, where a mem ory-access violation todayman ifests itself hou rs or d ays later. Programm ers can be confiden t that ar raychecking in Java will lead to more robu st and reliable code.

    2.1.4 Strings

    Strings are Java lang uage objects, not p seud o-arrays of characters as in C.There are actually two kinds of string objects: the String class is for read-only(immutable) objects. The StringBuffer class is for string objects you wish tomod ify (mu table string objects).

    Although strings are Java lang uage objects, Java comp iler follows the Ctradition of providing a syntactic convenience that C programmers haveenjoyed with C-style strings, namely, the Java comp iler u nd erstand s that a

    string of characters enclosed in d ouble qu ote signs is to be instantiated as aString object. Thus, the declaration:

    String hello = "Hello world!";

    2

  • 7/29/2019 Lang Environ

    22/98

    23 The JavaLanguage Environment M ay 1996

    2

    instantiates an object of the String class behind the scenes and initializes it witha character string containing the Un icode chara cter representation of "Helloworld! ".

    Java has extended the meaning of the + operator to indicate stringconcatenation . Thus you can write statements like:

    System.out.println("There are " + num + " characters in the file.");

    This code fragm ent concatenates the string "There are " with the result of converting the numeric value num to a string, and concatenates that with thestring " characters in the file." . Then it prints the resu lt of thoseconcatenations on the standard outpu t.

    String objects provide a length() accessor method to obtain the nu mber of characters in th e string.

    2.1.5 Multi-Level Break

    Java h as no goto statement. To break or continue multiple-nested loop orswitch constructs, you can p lace labels on loop and switch constructs, andthen break out of or continue to the block named by the label. Heres a smallfragment of code from Javas built-in String class:

    test : for (int i = fromIndex; i + max1

  • 7/29/2019 Lang Environ

    23/98

    JavaSimple and Familiar 24

    2

    alternatively, programmers have (mis)used the goto statement to exit out of nested blocks. Use of labelled blocks in Java leads to considerablesimplification in programming effort and a major reduction in maintenance.

    The notion of labelled blocks d ates back to the mid -1970s, but it hasnt caugh ton to any large extent in modern programming languages. Perl is anothermodern programming language that implements the concept of labelledblocks. Perls next label an d last label are equivalent to continue label an dbreak label statements in Java.

    2.1.6 Memory M anagement and Garbage Collection

    C and C++ programmers are by now accustomed to the problems of explicitlymanaging memory: allocating memory, freeing memory, and keeping track of what memory can be freed when. Explicit memory management has proved tobe a fruitful source of bugs, crashes, memory leaks, and poor performance.

    Java completely removes the mem ory man agemen t load from the progra mm er.C-style pointers, p ointer arithm etic, malloc, an d free do n ot exist. Automaticgarbage collection is an integral p art of Java an d its run-time system. While Javahas a new operator to allocate m emory for objects, there is no explicit freefunction. Once you h ave allocated an object, the run -time system keeps track of the objects status a nd autom atically reclaims mem ory w hen objects are nolonger in use, freeing memory for future use.

    Javas memory management model is based on objects an d references to o bjects.Java h as no pointers. Instead, a ll references to allocated storage, wh ich inpractice means all references to an object, are through symbolic hand les. TheJava m emory man ager keep s track of references to objects. When an object hasno m ore references, the object is a cand idate for gar bage collection.

    Javas memory allocation m odel and autom atic garbage collection make y ourprogram ming ta sk easier, eliminate entire classes of bugs, and in generalprovide better performance than youd obtain through explicit memorymanagement. Heres a code fragment that illustrates when garbage collectionhappens:

    class ReverseString {public static String reverseIt(String source) {

    int i, len = source.length();StringBuffer dest = new StringBuffer(len);

    for (i = (len - 1); i >= 0; i--) {

    2

  • 7/29/2019 Lang Environ

    24/98

    25 The JavaLanguage Environment M ay 1996

    2

    dest.appendChar(source.charAt(i));}return dest.toString();

    }}

    The variable dest is used as a temp orary object reference du ring execution of th e reverseIt method. When dest goes out of scope (the reverseItmethod returns), the reference to that object has gone away and its then acandid ate for garba ge collection.

    2.1.7 The Background Garbage Collector

    The Java gar bage collector achieves high p erformance by taking adv antage of the nature of a users behavior when interacting with software applicationssuch as th e H otJava brow ser. The typical user of the typ ical interactiveapplication has many natural pauses where theyre contemplating the scene infront of them or thinking of what to do next. The Java run-time system takesadv antage of these idle periods and run s the garbage collector in a low p rioritythread when no other threads are competing for CPU cycles. The garbagecollector gathers an d comp acts unu sed m emory, increasing th e probability that

    adequate m emory resources are available wh en needed du ring periods of heavy interactive use.

    This use of a thread to run the garba ge collector is just on e of many examplesof the synergy one ob tains from Javas integrated mu ltithread ingcapabilitiesan oth erwise intractable problem is solved in a simp le andelegant fashion.

    2.1.8 Integrated Thread SynchronizationJava supports multithreading, both at the language (syntactic) level and viasup port from its run-time system and thread ob jects. While other systems haveprovid ed facilities for multithread ing (usually via lightweight p rocesslibraries), building mu ltithread ing sup port into the langu age itself provides theprogrammer with a much easier and more powerful tool for easily creatingthread-safe multithreaded classes. Multithreading is discussed in more detailin Chapter 5.

    2

  • 7/29/2019 Lang Environ

    25/98

    JavaSimple and Familiar 26

    2

    2.2 Features Removed from C and C++The earlier pa rt of this chap ter concentrated on the p rincipal features of Java.

    This section discusses features removed from C and C++ in the evolution of Java.

    The first step was to eliminate redundancy from C and C++. In man y ways, the Clanguag e evolved into a collection of overlapping features, provid ing too man yways to say the same thing, while in m any cases not providing neededfeatures. C++, in an attempt to add classes in C, merely added moreredund ancy wh ile retaining m any of the inherent p roblems of C.

    2.2.1 No More Typedefs, Denes, or Preprocessor

    Source code written in Java is simple . There is no preprocessor , no #define an drelated capabilities, no typedef , and ab sent those features, no longer an y needfor header files . Instead of head er files, Java lang uage source files provide th edeclarations of other classes and their methods.

    A major problem with C and C++ is the amount of context you need tound erstand another programm ers code: you h ave to read all related head erfiles, all related #define s, and a ll related typedef s before you can even beginto analyze a program. In essence, program ming w ith #defines an d typedef sresults in every programmer inventing a n ew p rogramming language thatsincomprehen sible to anybod y other than its creator, thus d efeating th e goals of good programming practices.

    In Java, you obtain the effects of #define by u sing constants. You obta in theeffects of typedef by declaring classesafter all, a class effectively declares anew typ e. You d ont need hea d er files because th e Java comp iler com piles classdefinitions into a binary form that retains all the type information through tolink time.

    By remov ing all this baggage, Java becomes rem arkably context-free .Programmers can read and und erstand code and , more importantly, modifyand reuse code much faster and easier.

    2

  • 7/29/2019 Lang Environ

    26/98

    27 The JavaLanguage Environment M ay 1996

    2

    2.2.2 No More Structures or Unions

    Java ha s no structures or u nions as comp lex data ty pes. You d ont need

    structures and unions when you have classes; you can achieve the same effectsimply by declaring a class with the appropriate instance variables.

    The code fragm ent below declares a class called Point .

    class Point extends Object {double x;double y;

    // methods to access the instance variables}

    The following code fragm ent d eclares a class called Rectangle that usesobjects of the Point class as instance variables.

    class Rectangle extends Object {Point lowerLeft;Point upperRight;

    // methods to access the instance variables}

    In C you d define these classes as structures. In Java, you simply d eclare

    classes. You can m ake the instan ce variables as private or a s pu blic as youwish, depending on h ow m uch you w ish to hide the details of theimplemen tation from oth er objects.

    2.2.3 No Enums

    Java has no enum typ es. You can obta in someth ing similar to enum by d eclaring

    a class w hose only raison detre is to hold constants. You could u se this featuresomething like this:

    class Direction extends Object {public static final int North = 1;public static final int South = 2;public static final int East = 3;public static final int West = 4;

    }

    You can n ow refer to, say, the South constant using the notationDirection.South .

    2

  • 7/29/2019 Lang Environ

    27/98

    JavaSimple and Familiar 28

    2

    Using classes to contain constants in this wa y provid es a major advan tage overCs enum types. In C (and C++), nam es defined in enum s mu st be unique: if you have an enum called HotColors containing names Red an d Yellow , you

    cant use those names in any other enum . You could nt, for insta nce, defineanother Enum called TrafficLightColors also containing Red an d Yellow .

    Using the class-to-contain-constants techn ique in Java, you can u se the sam enam es in different classes, because th ose nam es are qualified by th e nam e of the containing class. From our example just above, you m ight w ish to createanother class called CompassRose :

    class CompassRose extends Object {public static final int North = 1;

    public static final int NorthEast = 2;public static final int East = 3;public static final int SouthEast = 4;public static final int South = 5;public static final int SouthWest = 6;public static final int West = 7;public static final int NorthWest = 8;

    }

    There is no ambiguity because th e nam e of the containing class acts as a

    qualifier for the constants. In the second example, you would use the notationCompassRose.NorthWest to access the corresponding value. Java effectivelyprovid es you th e concept of qu alified enum s, all within the existing classmechanisms.

    2.2.4 No More Functions

    Java ha s no functions . Object-oriented programming supersedes functional and

    procedu ral styles. Mixing the two styles just leads to confusion and dilutes thepurity of an object-oriented language. Anything you can do with a functionyou can do just as w ell by d efining a class and creating meth ods for that class.Consider the Point class from above. Weve ad ded pu blic method s to set andaccess the instance variables:

    class Point extends Object {double x;double y;

    public void setX(double x) {this.x = x;

    }

    2

  • 7/29/2019 Lang Environ

    28/98

    29 The JavaLanguage Environment M ay 1996

    public void setY(double y) {this.y = y;

    }public double x() {

    return x;}public double y() {

    return y;}

    }

    If the x an d y instance variables are private to this class, the only mean s toaccess them is via the p ublic method s of the class. Heres how youd u se

    objects of the Point class from within, say, an object of the Rectangle class:class Rectangle extends Object {

    Point lowerLeft;Point upperRight;

    public void setEmptyRect() {lowerLeft.setX(0.0);lowerLeft.setY(0.0);upperRight.setX(0.0);

    upperRight.setY(0.0);}}

    Its not to say that functions and procedures are inherently wrong. But givenclasses and m ethod s, were now d own to only one way to express a given task.By eliminating functions, your job as a progr amm er is immensely simplified:you work only with classes and their methods.

    2.2.5 No More Mult iple Inheritance M ultiple in heritance and all the problems it generateswas discarded fromJava. The desirable features of multiple inheritance are provided byinterfaces conceptually similar to Objective C protocols.

    An interface is not a definition of a class. Rather, its a definition of a set of methods that one or more classes will implement. An important issue of interfaces is that they d eclare only meth ods an d constan ts. Variables may not

    be d efined in interfaces.

    2

  • 7/29/2019 Lang Environ

    29/98

    JavaSimple and Familiar 30

    2.2.6 No More Goto Statements

    Java h as no goto statement *. Stud ies illustrated that goto is (mis)used m ore

    often than not simp ly because its there. Eliminating goto led to asimplification of the langu agethere are no rules abou t the effects of a gotointo the middle of a for statement, for example. Studies on approximately100,000 lines of C code d etermined that rou ghly 90 percent of the gotostatements were used purely to obtain the effect of breaking out of nestedloops. As mentioned above, mu lti-level break an d continue remove most of the need for goto statements.

    2.2.7 No More Operator OverloadingThere are no means p rovided by w hich p rogrammers can overload thestand ard arithmetic operators. Once again, the effects of operator overloadingcan be just as easily achieved by d eclaring a class, app ropriate instancevariables, and appropriate methods to manipulate those variables. Eliminatingoperator overloading leads to great simplification of code.

    2.2.8 No More Automatic Coercions

    Java p rohibits C and C++ style automatic coercions. If you wish to coerce a d ataelement of one type to a data type that would result in loss of precision, youmust do so explicitly by using a cast. Consider this code fragment:

    int myInt;double myFloat = 3.14159;

    myInt = myFloat;

    The assignment of myFloat to myInt would result in a compiler errorindicating a possible loss of precision and that you mu st use an explicit cast.Thus, you should re-write the code fragments as:

    int myInt;double myFloat = 3.14159;

    myInt = (int)myFloat;

    * However, goto is still a reserved word .

    2

  • 7/29/2019 Lang Environ

    30/98

    31 The JavaLanguage Environment M ay 1996

    2.2.9 No More Pointers

    Most studies agree that pointers are one of the primary features that enable

    program mers to inject bugs into their code. Given tha t structures are gone, andarrays an d strings are objects, the need for pointers to these constructs goesaway. Thus, Java has no pointer data types. Any task that would requirearrays, structures, and p ointers in C can be m ore easily and reliably performedby d eclaring ob jects and arrays of objects. Instead of comp lex pointermanipulation on array pointers, you access arrays by their arithmetic indices.The Java ru n-time system checks all array ind exing to en sure ind ices are withinthe bounds of the array.

    You no longer h ave da ngling pointers and trashing of memory becau se of incorrect p ointers, because th ere are no pointers in Java.

    2.3 SummaryTo sum up this chapter, Java is: Simplethe nu mber of language constructs you need to und erstand to get

    your job done is minimal. Familiar Java looks like C and C++ while discarding the overwhelming

    complexities of those langu ages.

    Now that you ve seen how Java w as simplified by remov al of features from itspredecessors, read the next chapter for a discussion on the object-oriented features of Java.

  • 7/29/2019 Lang Environ

    31/98

    32

    Javais Object Oriented 3

    My Object All SublimeI Will Achieve in Time

    Gilbert and Sullivan The M ikado

    To stay abreast of m odern software d evelopmen t p ractices, Java is object oriented from the ground up . The p oint of d esigning an object-orientedlanguage is not simply to jump on the latest programming fad. The object-oriented paradigm meshes well with the needs of client-server and distributedsoftware. Benefits of object technology are rap idly becoming realized as m oreorganizations move their applications to the distributed client-server model.

    Unfortun ately, object oriented rem ains misun derstood , over-mar keted as thesilver bu llet that will solve all our software ills, or takes on the trap pings of areligion. The cyn ics view of object-oriented pr ogra mm ing is that its just a n ewway to organize your source code. While there may be som e merit to this view,it doesnt tell the w hole story, because you can achieve results w ith object-oriented programming techniques that you cant with procedural techniques.

    An imp ortant chara cteristic that d istingu ishes objects from ord inaryprocedu res or functions is that an object can h ave a lifetime greater than th at of

    the object tha t created it. This aspect of objects is su btle and most ly overlooked .

    3

  • 7/29/2019 Lang Environ

    32/98

    33 The JavaLanguage Environment M ay 1996

    In the d istributed client-server w orld, you now have th e potential for objects tobe created in one place, passed around networks, and stored elsewhere,possibly in databases, to be retrieved for future work.

    As an object-oriented language, Java draws on the best concepts and featuresof previous object-oriented languages, primarily Eiffel, SmallTalk, Objective C,and C++. Java goes beyond C++ in both extending the object model andremoving the m ajor comp lexities of C++. With th e exception of its primitivedata ty pes, everything in Java is an object, and even the p rimitive types can beencapsu lated w ithin objects if the need arises.

    3.1 Object Technology in JavaTo be truly considered object oriented, a programming language shouldsupport at a minimum four characteristics: Encapsulation implements information hiding and modularity (abstraction) Polymorphism the same message sent to different objects results in behavior

    thats dependent on the nature of the object receiving the message Inheritance you d efine new classes and behavior based on existing classes

    to obtain code re-use and code organization Dynamic binding objects could come from an yw here, possibly across the

    netw ork. You n eed to be able to send messages to objects without h aving toknow their specific type at the time you write your code. Dynamic bindingprovid es maximu m flexibility while a progra m is executing

    Java meets these requirements nicely, and adds considerable run-time supportto make your software development job easier.

    3.2 W hat AreObjects?At its simplest, object technology is a collection of analysis, design, andprogramming methodologies that focuses design on modelling th echaracteristics an d behavior of objects in the real wor ld. True, th is definitionapp ears to be som ewh at circular, so lets try to break ou t into clear air.

    What are objects? Theyre software p rogramm ing models . In your everyd ay life,

    youre surroun ded by objects: cars, coffee machines, ducks, trees, and so on.Software ap plications contain objects: buttons on u ser interfaces, spreadsh eets

    3

  • 7/29/2019 Lang Environ

    33/98

    Java is Object Orient ed 34

    and spread sheet cells, prop erty lists, menus, and so on. These objects have statean d behavior . You can represent all these things w ith software constru cts calledobjects, wh ich can also be defined by their state and their behavior .

    In your everyday transportation needs, a car can be mod elled by an object. Acar has state (how fast its going, in w hich d irection, its fuel consum ption, andso on) and behavior (starts, stops, turn s, slides, and run s into trees).

    You d rive you r car to your office, w here you t rack you r stock portfolio. In you rdaily interactions w ith the stock markets, a stock can be mod elled by an object.A stock has state (daily high, da ily low, open p rice, close price, earnings pershare, relative strength ), and behavior (chan ges value, performs sp lits, hasdividends).

    After watching you r stock decline in p rice, you rep air to the cafe to consoleyourself with a cup of good h ot coffee. The espresso machine can be modelled asan object. It has state (water temperature, amount of coffee in the hopper) andit has behavior (emits steam, makes noise, and brews a perfect cup of java ).

    3.3 Basics of Objects

    An objects behavior is defined by its methods . Methods manipulate the instancevariables to create new state; an objects m ethod s can also create new objects.

    The small picture to the left is a commonly u sed gra ph ical representation of anobject. The d iagram illustrates the conceptu al structure of a softwa reobjectits kind o f like a cell, w ith an ou ter mem bran e thats its interface to theworld, and an inner n ucleus thats protected by th e outer mem brane.

    An objects instance variables (data) are packaged, or encapsulated, within theobject. The instan ce variables are surrou nd ed by th e objects methods . Withcertain w ell-defined exceptions, the objects meth ods are the on ly mean s by

    Inst anceVariables

    Method

    Method

    M e t h o d M

    e t h o d

    3

  • 7/29/2019 Lang Environ

    34/98

    35 The JavaLanguage Environment M ay 1996

    w hich oth er objects can access or alter its instance var iables. In Java, classes candeclare their instance variables to be public , in w hich cases the instancevariables are globally accessible to other objects. Declarations of accessibility

    are covered later in A ccess Specifiers . Later on you will also find a discussion onclass variables and class method s.

    3.3.1 Classes

    A class is a software construct that defines the data (state) and methods(behavior) of the specific concrete objects that are su bsequently constructedfrom that class. In Java terminology, a class is built out of members , which areeither fields or methods . Fields are the d ata for the class. Method s are thesequences of statements that op erate on th e data. Fields are n ormally specificto an objectthat is, every object constructed from the class definition willhave its ow n copy of the field. Such fields are k now n as instance variables.Similarly, method s are also normally d eclared to op erate on th e instancevariables of the class, and are thus known as instance methods .

    A class in and of itself is not an object. A class is like a bluep rint th at d efineshow an object will look and behave when the object is created or instantiated from th e specification d eclared by th e class. You o btain con crete objects byinstan tiating a pr eviou sly defined class. You can insta ntiate m any ob jects fromone class definition, just as you can construct man y hou ses all the same * from asingle architects d raw ing. H eres the basic declaration of a very simp le classcalled Point

    class Point extends Object {public double x; /* instance variable */public double y; /* instance variable */

    }

    As mentioned, this declaration merely defines a template from which realobjects can be instantiated, as d escribed next.

    * Like those Little Boxes.

    3

  • 7/29/2019 Lang Environ

    35/98

    Java is Object Orient ed 36

    3.3.2 Instant iating an Object from its Class

    Having declared the size and shape of the Point class above, any other ob ject

    can now create a Point object an instance of the Point classwith afragment of code like this:

    Point myPoint; // declares a variable to refer to a Point object

    myPoint = new Point(); // allocates an instance of a Point object

    Now, you can access the variables of this Point object by referring to the namesof the variables, qualified w ith the n ame of th e object:

    myPoint.x = 10.0;

    myPoint.y = 25.7;

    This referencing scheme, similar to a C structure reference, works becau se theinstance variables of Point were declared public in the class d eclaration.Had the instance variables not been declared public , objects outside of thepackage within which Point w as declared could not access its instancevariables in this direct man ner. The Point class declaration would then needto provide accessor methods to set and get its variables. This topic is discussed ina little more detail after this discussion on constru ctors.

    3.3.3 Constructors

    When y ou d eclare a class in Java, you can d eclare optional constructors thatper form initialization w hen y ou insta ntiate objects from tha t class. You can alsodeclare an optional finalizer , discussed later. Lets go back to our Point classfrom before:

    class Point extends Object {public double x; /* instance variable */public double y; /* instance variable */

    Point() { /* constructor to initialize to default zero value */x = 0.0;y = 0.0;

    }/* constructor to initialize to specific value */

    Point(double x, double y) {this.x = x; /* set instance variables to passed parameters */

    this.y = y;}

    }

    3

  • 7/29/2019 Lang Environ

    36/98

    37 The JavaLanguage Environment M ay 1996

    Methods with the same name as the class as in the code fragment are calledconstructors . When you create (instantiate) an object of the Point class, theconstructor method is invoked to perform any initialization thats neededin

    this case, to set the instan ce variables to an initial state.This examp le is a variation on the Point class from before. Now, wh en youwish to create and initialize Point objects, you can get them initialized to theirdefault valu es, or you can initialize them to specific values:

    Point lowerLeft;Point upperRight;

    lowerLeft = new Point(); /* initialize to default zero value */upperRight = new Point(100.0, 200.0); /* initialize to non- zero */

    The specific constru ctor thats used wh en creating a n ew Point object isdetermined from the type and num ber of parameters in the new invocation.

    The this Variable

    Whats the this variable in the examples above? this refers to the objectyoure in right now. In other words, this refers to the receiving o bject. Youuse this to clarify wh ich v ariable youre referring to. In the tw o-param eter

    Point method, this.x means the x instance variable of this object, rath erthan the x parameter to the Point method.

    In the examp le above, the constru ctors are simp ly conveniences for the Pointclass. Situations arise, however, where constructors are necessary, especially incases where th e object being instantiated mu st itself instantiate other objects.Lets illustrate one of those situations by declaring a Rectangle class that u sestw o Point objects to define its boun ds:

    class Rectangle extends Object {private Point lowerLeft;

    private Point upperRight;

    Rectangle() {lowerLeft = new Point();upperRight = new Point();

    }. . .

    instance methods appear in here. . .

    }

    3

  • 7/29/2019 Lang Environ

    37/98

    Java is Object Orient ed 38

    In this example, the Rectangle constructor is vitally necessary to ensu re thatthe two Point objects are instantiated at th e time a Rectangle object isinstantiated, otherwise, the Rectangle object would subsequently try to

    reference points that have not yet been allocated, and would fail.

    3.3.4 Methods and M essaging

    If an object w ants an other object to d o some w ork on its behalf, then in th eparlance of object-oriented program ming, th e first object sends a message to thesecond object. In response, the second ob ject selects the ap prop riate method toinvoke. Java m ethod invocations look similar to functions in C an d C++.

    Using the message passing paradigms of object-oriented programming, youcan build entire networks and webs of objects that pass messages betweenthem to change state. This programming technique is one of the best ways tocreate models and simulations of complex real-wor ld system s. Lets redefine

    the d eclaration of the Point class from above such th at its instance variablesare private , and sup ply it with accessor methods to access those variables.

    class Point extends Object {private double x; /* instance variable */private double y; /* instance variable */

    Point() { /* constructor to init ialize to zero */x = 0.0;y = 0.0;

    } /* constructor to initialize to specific value */Point(double x, double y) {

    Insta nce

    Variables

    Method

    Method

    M e t h o d M

    e t h o d

    Insta nce

    Variables

    Method

    Method

    M e t h o d M

    e t h o d

    Messa ge

    3

  • 7/29/2019 Lang Environ

    38/98

    39 The JavaLanguage Environment M ay 1996

    this.x = x;this.y = y;

    }public void setX(double x) { /* accessor method */

    this.x = x;}public void setY(double y) { /* accessor method */

    this.y = y;}public double getX() { /* accessor method */

    return x;}public double getY() { /* accessor method */

    return y;}

    }

    These method d eclarations provide the flavor of how the Point class prov idesaccess to its variables from the ou tside w orld. Anoth er object that w ants tomanipulate the instance variables of Point objects must now do so via theaccessor methods:

    Point myPoint; // declares a variable to refer to a Point object

    myPoint = new Point(); // allocates an instance of a Point object

    myPoint.setX(10.0); // sets the x variable via the accessor method myPoint.setY(25.7);

    Making instan ce variables public or private is a design trad eoff thedesigner m akes wh en d eclaring the classes. By m aking instance variablespublic , you expose details of the class implementation, thereby providinghigher efficiency and conciseness of expression at th e p ossible expense of hind ering futu re maintenan ce efforts. By hid ing d etails of the internalimplementation of a class, you have the potential to change theimplementation of the class in the future without breaking any code that usesthat class.

    3.3.5 Finalizers

    You can also d eclare an option al finalizer that will perform necessary teardownactions w hen the garb age collector is about to free an object. This code

    fragment illustrates a finalize method in a class.

    3

  • 7/29/2019 Lang Environ

    39/98

    Java is Object Orient ed 40

    /*** Close the stream when garbage is collected.*/

    protected void finalize() {

    try {file.close();

    } catch (Exception e) {}

    }

    This finalize meth od w ill be invoked wh en the object is about to be garbagecollected, which means that the object must shut itself down in an orderlyfashion. In the particular code fragment above, the finalize method merely

    closes an I/ O file stream th at w as u sed by the object, to ensure that th e filedescriptor for the stream is closed.

    3.3.6 Subclasses

    Subclasses are the mechanism by which new and enhanced objects can bedefined in terms of existing objects. One exam ple: a zebra is a h orse w ithstripes. If you w ish to create a zebra object, you notice that a zebra is kind of like a h orse, only w ith stripes. In object-oriented terms, you d create a newclass called Zebra, which is a subclass of the H orse class. In Java langu ageterms, youd do something like this:

    class Zebra extends Horse {Your new instance variables and new methods go here

    }

    The d efinition of Horse , wherever it is, would define all the methods todescribe the behavior of a horse: eat, neigh, trot, gallop, bu ck, and so on. Theonly method you n eed to override is the method for draw ing the hide. Yougain the benefit of already w ritten code that d oes all the w orkyou d ont haveto re-invent the wheel, or in this case, the hoof. The extends keyw ord tells theJava comp iler that Z ebra is a subclass of Hor se. Zebra is said to be a derived class its d erived from Hor se, which is called a superclass .

    Heres an exam ple of making a subclass, wh ich is a variant of our Point classfrom previous examples to create a new three-dimensional point calledThreePoint :

    class Point extends Object {protected double x; /* instance variable */protected double y; /* instance variable */

    3

  • 7/29/2019 Lang Environ

    40/98

    41 The JavaLanguage Environment M ay 1996

    Point() { /* constructor to init ialize to zero */x = 0.0;y = 0.0;

    }}

    class ThreePoint extends Point {protected double z; /* the z coordinate of the point */

    ThreePoint() { /* default constructor */x = 0.0; /* initialize the coordinates */y = 0.0;z = 0.0;

    }ThreePoint(double x, double y, double z) {/* specific constructor */this.x = x; /* initialize the coordinates */this.y = y;this.z = z;

    }}

    Notice that ThreePoint adds a new instance variable for the z coordinate of the point. The x an d y instance variables are inherited from the original Point

    class, so theres no need to d eclare them in ThreePoint . However, notice wehad to make Point s instance variables protected instead of private as inthe previous examples. Had we left Point s instance variables private , evenits subclasses would be unable to access them, and the compilation would fail.

    Subclasses enable you to use existing code thats already been developed and,mu ch more imp ortant, tested, for a more generic case. You ov erride the p arts of the class you n eed for you r sp ecific behavior. Thus, sub classes gain you reuse

    3

  • 7/29/2019 Lang Environ

    41/98

    Java is Object Orient ed 42

    of existing codeyou save on design, development, and testing. The Java run-time system p rovides several libraries of utility functions that are tested an dare also thread safe .

    All classes in Java ultimately inherit from Object . Object is the most generalof all the classes. New classes that you declare add functionality to th eirsup erclasses. The furth er dow n the class hierarchy you gothat is, the furtheryou get from Object the more sp ecialized your classes become.

    Single Inheritance and the Class Hierarchy

    Java implements what is know n as a single-inheritance mod el. A new class cansubclass ( extend , in Java terminology) only one other class. Ultimately, allclasses eventually inherit from th e Object class, forming a tree structure withObject as its root. This p icture illustrates th e class hierarchy of the classes inthe Java utility package, java.util.

    The HashTable class is a subclass of Dictionary , which in turn is a subclassof Object . Dictionary inherits all of Object s variables and methods(behavior), then ad ds n ew v ariables and beh avior of its own. Similarly,HashTable inherits all of Object s variables and behavior, plus all of Dictionary s variables and behavior, and goes on to add its own variablesand behavior.

    Then the Properties class subclasses HashTable in turn, inheriting all thevariables and behavior of its class hierarchy. In a similar m ann er, Stack an dObserverList are su bclasses of Vector , which in turn is a subclass of Object . The power of the object-oriented methodology is apparentnone of the su bclasses needed to re-imp lement th e basic fun ctionality of theirsuperclasses, but needed only add their own specialized behavior.

    3

  • 7/29/2019 Lang Environ

    42/98

    43 The JavaLanguage Environment M ay 1996

    How ever, the above diagram p oints out the minor w eakness with the single-inheritance model. Notice that there are two different kinds of enumerator classes in the p icture, both of wh ich inh erit from Object . An enumerator class

    implemen ts behavior tha t iterates through a collection, obtaining the elementsof that collection on e by on e. The enum erator classes define behavior th at bothHashTable an d Vector find useful. Other, as yet undefined collection classes,such as list or queue, may also need the behavior of the enumeration classes.Unfortun ately, they can inherit from only on e sup erclass.

    HashtableEnumerator

    HashtableEntry

    Dictionary

    Properties

    Hashtable

    BitSet

    Observable

    Stack ObserverList

    Vector

    VectorEnumerator

    Object

    3

  • 7/29/2019 Lang Environ

    43/98

    Java is Object Orient ed 44

    A possible meth od to solve this problem wou ld be to enhan ce some sup erclassin the hierarchy to add such useful behavior when it becomes apparent thatman y subclasses could u se the behavior. Such an ap proach w ould lead to chaosand bloat. If every time some common useful behavior were required for allsubsequ ent su bclasses, a class such as Object wou ld be und ergoing constantmodification, would grow to enormous size and complexity, and thespecification of its behavior would be constantly changing. Such a solution isuntenable. The elegant and workable solution to the problem is provided viaJava interfaces , the su bject of the next top ic.

    3.3.7 Java Language Interfaces

    Interfaces were introd uced to Java to enhan ce Javas single-inh eritance mod el.The designers of Java decided that multiple inheritance created too manyproblems for programmers and compiler writers, and decided that a singleinheritance model was better overall. Some of the problems described in theprevious discussion on the single-inheritance model are solved in a moreelegant fashion by th e u se of interfaces.

    An interface in the Java languag e is simp ly a specification of method s that anobject declares it imp lements. An interface d oes not includ e instance variablesor implementation codeonly declarations of constants and methods. Theconcept of an interface in the Java languag e wa s borrow ed from th e Objective-C concept of a protocol .

    Whereas a class can inherit from on ly one su perclass, a class can implement asman y interfaces as it chooses to. Using the examp les from th e previousdiscussion, the HashTableEnumerator an d VectorEnumerator classes bothimplement an Enumeration interface tha ts specific to the chara cteristics of th e HashTable an d Vector classes. When you define a new collectionclassa Queue class, for instanceyoull also probably define aQueueEnumerator class that implements the Enumeration interface.

    The concept of the interface is pow erfulclasses that imp lement a giveninterface need do so only at th e app ropriate level in the class hierarchy. Thispicture illustrates the use of interfaces.

    3

  • 7/29/2019 Lang Environ

    44/98

    45 The JavaLanguage Environment M ay 1996

    In this illustration, interfaces are represented by rectangles. You see that th e

    Cloneable interface is implemented by m ultiple classes. In ad dition, theHashtableEnumerator and the VectorEnumerator classes both imp lement

    HashtableEnumerator

    Enumeration

    HashtableEntry

    Dictionary

    Cloneable

    Properties

    Hashtable

    BitSet

    Cloneable

    Observable

    Cloneable

    Stack ObserverList

    Vector

    VectorEnumerator

    Enumeration

    VectorEnumerator

    Object

    3

  • 7/29/2019 Lang Environ

    45/98

    Java is Object Orient ed 46

    th e Enumeration interface. Any given class can implemen t as ma ny interfacesas it wants to, and in any way that it wants to. Details of the actualimplementation of the interface are hidden within the class definition, andshould be replaceable withou t affecting th e outside view of the interface in anyway. Recall, howev er, that an interface merely declares method s; it does not

    implemen t them. When inh eriting from classes (in languages such as C++), theimplemen tation of inherited classes is also inherited, so m ore code can bereused when compared to the amount of code re-use in multiply-inheritedinterfaces. For this reason, inheriting from interfaces provides a reasonablealternative to multiple inheritance, but this practice should not be seen as asubstitute for the more powerful but often confusing practice of inheritingfrom multiple classes.

    3.3.8 A ccess Control

    When you declare a new class in Java, you can ind icate the level of accesspermitted to its membersthat is, its instance variables and methods. Javaprovides four levels of access. Three of the levels must be explicitly specified:public , protected , and private . Members d eclared public are a vailableto any oth er class anyw here. Members declared protected are accessible onlyto subclasses of that class, and now here else. Members declared private areaccessible only from within the class in w hich theyre declaredtheyre notavailable even to th eir subclasses.

    The fourth access level doesnt have a nameits often called friendly and isthe access level you ob tain if you d ont specify otherw ise. The friend lyaccess level indicates that the classs members are accessible to all objects

    within th e same p ackage, but inaccessible to objects outside the p ackage.Packages, a useful tool for grou ping together related collections of classes andinterfaces, are discussed below.

    3.3.9 Packages

    Java packages are collections of classes and interfaces that are related to eachother in some u seful w ay. Such classes need to be able to access each other sinstance variables and m ethod s directly. A geometry p ackage consisting of Point an d Rectangle classes, for instan ce, might w ell be easier an d cleanerto imp lementas w ell as more efficientif the Point s instance variables

    3

  • 7/29/2019 Lang Environ

    46/98

    47 The JavaLanguage Environment M ay 1996

    were d irectly available to the Rectangle class. Outside of the geom etrypackage, however, the details of implementations are hidden from the rest of the world, giving you the freedom to changed implementation details withoutwor rying you ll break code that u ses those classes. Packages are created bystoring the source files for the classes and interfaces of each p ackage in aseparate d irectory in the file system.

    The prim ary ben efit of packages is the ability to orga nize ma ny classdefinitions into a single unit. For example, all the Java I/ O system code iscollected into a sin gle packag e called java.io . The second ary ben efit from theprogrammers viewpoint is that the friendly instance variables and methodsare available to all classes within the same p ackage, but n ot to classes d efinedoutside the p ackage.

    3.3.10 Class Variables and Class Methods

    Java follows conventions from oth er object-oriented lang uages in provid ingclass methods an d class variables . Nor mally, variables you declare in a classdefinition are instance variables there is one of those variables in everyseparate ob ject created (instantiated) from the class. A class variable, on th eother hand, is local to the class itselftheres only a single copy of the variableand its shared by every object you instan tiate from the class.

    To d eclare class variables and class meth ods in Java p rogram s, you d eclarethem static . This short code fragm ent illustrates the d eclaration of classvariables:

    class Rectangle extends Object {static final int version = 2;static final int revision = 0;

    }

    The Rectangle class declares two static variables to define the version an drevision level of this class. Now, every instance of Rectangle you create fromthis class w ill share th ese same v ariables. Notice theyre also defined as finalbecause you wan t them to be constants.

    Class methods are common to an entire class. When would you use classmethod s? Usually, wh en you have beh avior thats comm on to every ob ject of aclass. For example, suppose you have a Window class. A u seful item of

    information you can ask the class is the current number of currently openwind ow s. This information is shared by every instance of Window and it is

    3

    l il bl h h k l d b i d f h i f Wi d

  • 7/29/2019 Lang Environ

    47/98

    Java is Object Orient ed 48

    only available through knowledge obtained from other instances of Window .For these reasons, it is necessary to have just one class method to return th enumber of open windows.

    In general, class method s can operate on ly on class variables. Class method scant access instance variables, nor can they inv oke instance m ethod s. Likeclass variables, you declare class method s by d efining them as static .

    We say, in general, because you could pass an object reference to a classmethod, and the class method could then operate on the objects publicinstance variables, and invoke th e objects instance m ethod s via th e reference.How ever, youre usu ally better off doing only class-like op erations at th e classlevel, and doing object-like operations at the object level.

    3.3.11 A bstract M ethods

    Abstract method s are a pow erful constru ct in th e object-oriented p arad igm. Toun derstan d abstract method s, w e look at the notion of an abstract superclass . Anabstract superclass is a class in w hich you declare method s that arent actuallyimplemented by that classthey only provide place-holders that subsequentsubclasses must override and supply their actual implementation.

    This all soun ds w ond erfully, well, abstract , so why wou ld you need an abstractsuperclass? Lets look at a concrete example, no pu n intended . Lets sup poseyoure going to a restaurant for dinner, and you decide that tonight you wantto ea t fish. Well, fish is somewhat abstractyou generally wouldnt just orderfish; the w aiter is highly likely to ask you wh at specific kind of fish you want.When you actually get to the restaurant, you will find out what kind of fishthey ha ve, and order a specific fish, say, sturgeon, or salmon , or opak apak a.

    In the world of objects, an abstract class is like generic fishthe abstract classdefines generic state and generic behavior, but youll never see a real liveimplemen tation of an abstract class. What you will see is a concrete subclass of the abstract class, just as opakapaka is a specific (concrete) kind of fish.

    Suppose you are creating a drawing application. The initial cut of yourapp lication can d raw rectangles, lines, circles, polygons, and so on.Furthermore, you have a series of operations you can perform on theshap esmove, resh ap e, rotate, fill color, and so on. You could make each of these grap hic shapes a separate classyoud h ave a Rectangle class, a Line

    3

    class and so on Each class needs instance variables to define its position size

  • 7/29/2019 Lang Environ

    48/98

    49 The JavaLanguage Environment M ay 1996

    class, and so on. Each class needs instance variables to define its position, size,color, rotation and so on, wh ich in tu rn d ictates method s to set and get at th osevariables.

    At this point, you realize you can collect all the instance variables into a singleabstract superclass called Graphical , and imp lement m ost of the methods toman ipulate the v ariables in th at abstract sup erclass. The skeleton of yourabstract superclass might look something like this:

    abstract class Graphical extends Object {protected Point lowerLeft; // lower left of bounding boxprotected Point upperRight; // upper right of bounding box

    . . .more instance variables

    . . .public void setPosition(Point ll, Point ur) {

    lowerLeft = ll;upperRight = ur;

    }abstract void drawMyself(); // abstract method

    }

    Now, you cant instantiate the Graphical class, because its declaredabstract . You can only instantiate a subclass of it. You w ould implemen t theRectangle class or the Circle class as a subclass of Graphical . WithinRectangle , youd provide a concrete implementation of the drawMySelfmethod that d raw s a rectangle, because the d efinition of drawMySelf mu st bynecessity be unique to each shape inherited from the Graphical class. Letssee a small fragm ent of the Rectangle class d eclaration, w here itsdrawMySelf method operates in a somewhat PostScripty fashion:

    class Rectangle extends Graphical {void drawMySelf() { // really does the drawing

    moveTo(lowerLeft.x, lowerLeft.y);lineTo(upperRight.x, lowerLeft.y);lineTo(upperRight.x, upperRight.y)lineTo(lowerLeft.x, upperRight.y);

    . . .and so on and so on

    . . .}

    }

    3

    Notice however that in the d eclaration of the Graphical class the

  • 7/29/2019 Lang Environ

    49/98

    Java is Object Orient ed 50

    Notice, however, that in the d eclaration of the Graphical class, thesetPosition method was d eclared as a regular ( public void ) method. Allmethods that can be implemented by the abstract superclass can be declaredthere and their implementations defined at that time. Then, every class thatinherits from the abstract sup erclass will also inherit those m ethod s.

    You can continue in this way ad ding n ew sha pes that are subclasses of Graphical , and most of the time, all you ever need to implement is themethod s that are un ique to th e specific shap e. You gain the benefit of re-usingall the code that was defined inside the abstract superclass.

    3.4 SummaryThis chap ter has conveyed the essential aspects of Java as an object-oriented language. To sum up : Classes define templates from w hich you instantiate (create) distinct concrete

    objects . Instance variables hold the state of a specific object. Objects communicate by sending messages to each other. Objects respon d to

    messages by selecting a method to execute. Methods define the behavior of objects instantiated from a class. It is an

    objects meth ods th at m anipu late its instance variables. Unlike regularprocedural languages, classes in an object-oriented language may havemeth ods w ith the same n ames as other classes. A given object respond s to amessage in ways determined by the nature of that object, providing

    polymorphic behavior. Subclasses provide the means by which a new class can inherit instance

    variables and methods from any already defined class. The newly declaredclass can add new instance variables (extra state), can add new methods(new beh avior), or can override the m ethod s of its superclass (differentbehavior). Subclasses provide cod e reuse.

    Taken togeth er, the concepts of object-oriented p rogramm ing create a p owerfuland simple paradigm for software developers to share and re-use code andbuild on the w ork of others.

    3

  • 7/29/2019 Lang Environ

    50/98

    51 The JavaLanguage Environment M ay 1996

  • 7/29/2019 Lang Environ

    51/98

    50

    ArchitectureN eutral, Portable,andRobust 4

    With the phenom enal growth of netw orks, todays d evelopers mu st think distributed. Applicationseven parts of applicationsmust be able tomigrate easily to a wide variety of computer systems, a wide variety of

    hardware architectures, and a wide variety of operating system architectures.They must operate with a plethora of graphical user interfaces.

    Clearly, applications mu st be able to execute an ywh ere on the netw ork w ithoutprior knowledge of the target hardware and software platform. If applicationdevelopers are forced to d evelop for specific target platforms, the binarydistribution problem quickly becomes unmanageable. Various and sundrymethods have been employed to overcome the problem, such as creating fatbinaries that adap t to the specific hard wa re architecture, but such meth ods are

    not only clumsy but are still geared to a specific operating system. To solve thebinary-distribution problem, software applications and fragments of applications must be architectu re neutral an d portable .

    Reliability is also at a high premium in the distributed world. Code fromanywhere on the network should work robustly with low p robabilities of creating crashes in applications that import fragments of code.

    This chapter describes the ways in which Java has addressed the issues of architecture neutrality, portability, and reliability.

    4

    4.1 ArchitectureNeutral

  • 7/29/2019 Lang Environ

    52/98

    51 The JavaLanguage Environment M ay 1996

    4.1 ArchitectureNeutralThe solution that the Java system adopts to solve the binary-distributionproblem is a binary code format thats independent of hardwarearchitectures, operating system interfaces, and wind ow system s. The format of this system-independent binary code is architectu re neutral . If the Java run-timeplatform is mad e available for a given hardw are and software environm ent, anapplication written in Java can then execute in that environment without theneed to perform any special porting work for that application.

    4.1.1 Byte Codes

    The Java comp iler d oesnt generate m achine code in the sense of nativehardware instructionsrather, it generates bytecodes : a h igh-level, machine-independent code for a hypothetical machine that is implemented by the Javainterpreter and run-time system.

    One of the early examples of the bytecode approach was the UCSD P-System,wh ich w as ported to a variety of eight-bit architectures in the m idd le 1970s andearly 1980s and enjoye