Download as pdf
Download as pdf
You are on page 1of 22
Fundamentals of Object-Oriented Programming ms structured Programming | Object-Oriented Paradigm | Class | Object | Method | Abstraction | | Encapsulation | Data Hiding | Inheritance | Reusabilty | Polymorphism | Dynamic Binding 4,1 INTRODUCTION one characteristic that is constant in the software industry today is “change”. Change is one of the eet cntieal aspects of software development and management. New tools and now ‘approaches are Saaounced almost everyday. The impact of these developments is often very extensive and raises umber of issues that must be addressed by the software engineers. Most important among them are rrntinabilty, reusability, portability, security, integrity, and user friendliness of software products. ‘To build today's complex software it is just not enough to put together @ sequerios of programming statements and sets of procedures and modules. We need fo use sound construction techniques and program structures that are easy to comprehend, implement and modify in a wide variety of situations. Since the invention of the computer, many programming approaches Nave been tried. These incude techniques such as modular programming, top-down programming, bottom-up programming oe tructured programming. The primary motivation in each case has been the concern to handle the increasing complexity of programs that are reliable and maintainable, These techniques became popular among programmers over the last two decades. Awan ihe advent of languages such as C, structured programming Became Yom popular and wos the paradigm of the 1980s. Structured programming proved to be powerful tool that enabled programmers to write moderately complex programs fairly easily. However, as the programs grew farger, even the structured approach failed to show the desired results in terms of bug-free, easy-to- maintain, and reusable programs. ‘Object Oriented Programming (OOP) is an approach to program organization and development, hier attempts. to eliminate some of the pitfalls of conventional programming methods by incorporating the best of structured programming features with ‘several new concepts. It is a new way Grorganizing and developing programs and has nothing to do with any particular language. However, wr at languages are suitable to implement the OOP concepts easily. Languages that support woe estivs include Smaltalk, Objective C, C++, Ada and Object Pascal. C+*. an extension of © language, is the most popular OOP language today. C++ is basically procedural language with ‘Scanned with CamScanner 9 tod extension. Java, @ pure objectoriented language, is one of the recent languages ‘er tus lst, the latest one being CH 1.2. OBJECT-ORIENTED PARADIGM ti f object-oriented approach is to Tate tome of the flaws encountered in the procedural Seoroa n OOP treats data as a critical element in the program seeetosment and does not allow it to flow freely around the ata more closely to thé functions that operate tects it from_unintentional modification, by other Rr ctane OOP "allows. us to-decomposaa problem )into a number of entities called (Objects) and then” build” data and functions (known as methods in Java) around these entities, The combination of data and methods make up an object AL : +e eta ‘oan object\can be accessed only by the methods associated with that object. However, methods of can access the methods of other objects. Some of th of object-oriented paradigm are: TERED Siac: Data + Methods 4. Emphasis is on datd rather than procedure. Programs’are divided into what are known as Objects. Data structures are designed such that they characterize the SbjectS) 2 . 7 4, Methods that operate on the data of an object are tied together 5. Data is hidden and cannot be accessed by external functions. 6 7. 8. data structure. Objects may communicate with each other through methods. New data and methods can be easily added whenever necessary. Follows bottom-up approach in program design. Object-oriented paradigm is the most recent concept among programming paradigms and means different things to different people. It is therefore important to have a working definition of object. oriented programming before we proceed further. Object-oriented programming is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. This means that an object is considered to be 2 partitioned area of computer memory that stores data and a set of operations that can access the data. Since the memory partitions are independent, the objects can be used in a variety of diferent programs without modifications, 1.3 BASIC CONCEPTS OF OBJECT-ORIENTED PROGRAMMING As mentioned earlier, object-oriented is a term, which is interpreted differently by different people. It is therefore necessary to understand some of the concepts used extensively in object-oriented Programming. We shall now discuss the general concepts of OOP which form the heart of Java language. Objects and Classes Objects are the basic runtime entities_in-an_obj place, a_bank account, a table of data or any represent user-defined data types such Ss oriented system. They may represent a person, m that the program may handle. They may also lors and lists. Any programming problem is analyzed in ‘Scanned with CamScanner Fundamentals of Object-Oriented Programming 3 terms of objects and the nature of communication between them. Program objects should be — chosen such that they match closely with the reakworld objects. As pointed out earlier, an object takes up space in the memory and has an oe associated address like a record in Pascal, or a structure in C. When a program is executed, the objects inleract by sending messages to one another For example, ‘customer’ and ‘account’ are. tw .tetode objects in a banking program, then the customer 'ssage to the account object sawesting for the balance. Each object contains data and code to manipulate the data, Objects Gan interact without having to know the details of It is sufficient to know the type of message accepted am Representation of an object Ithough different authors represent them differently, Fig. 1.2 shows fepresent an object in object-oriented analysis and design. data and contain data and code to manipulate that data. The entire set of Y be tho siCf an object can be made a user-defined data type using the concept of a class. A clase abe thought of as a ‘data type’ and an object as a ‘variate’ of Ural cats type. Once a class has pan oted, we can create any number of objects belonging to hat Gace earn object is associated im the data of type class with which they are created. A class is thus « celieclcn oy objects of similar ee. For example, mango, apple and orange are members ofthe class ful, Classes ans user-defined data types and behave like the built-in types of a programming language. For example, the syntax used to create an object is no dif ferent than the syntax used to create an integer object in C. If fruit has been defined as a class, then the statement @ notation that is popularly used to r We just mentioned that objects fruit mango; will create an object mango belonging to the class fruit. Data Abstraction and Encapsulation The wrapping up of data and methods into a single unit (called class) is known as encapsulation, Data encapsulation is the most striking fealure of a class. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it. These methods provide the interface between the object's data and the program{ This insulation of the data from direct access by the program jis called data hiding(Encapsulation makes it possible for objects to be treated like ‘black boxes’, each performing a specific task without any fn for internal implementationYsee Fig. 1.3). Abstraction refers to the act of fepresenting essential features without including the background details oF explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and methods that operate on these attributes. They encapsulate all the essential properties of the a objects that are to be created Ene ipsulation js. _/nformation “in” _ one of the three OOP principles, the other two being inheritance and polymorphism. The concept of data encapsulation and ab- straction can be well understood by consider- ing the simple example of a mobile phone. It is Data Information “out” and [ERE Encopsutation—onjects as “black boxes” ‘Scanned with CamScanner sail 4 Programming with Java a complex electronic d Ser gecuonic device, which s used for text and voice ammunition, How the intornal circuitry Tae eaT ae a ean uaae a ei Tomato person Is irrelevant from hig Yigwpolnt The only thing tha ho fs concamed about Is the fact that by pressing the green “Ansviit vinitawel encecant ae the other aldo, Thus, the usor is Isolated from all tho complex circuitry ia is well encapsutaed within the mobile phono meee th standard operations tha can bo performed with a mobile phono-—daling A a receiving 8 call, sending end recalving laxt messages, oo en gonsidor the common data elemon's ea in all types of mobile phones, i... addross book, Inbox. sent itoms, etc, We can refer to these sls of dats and operations a8 n abstraction of a 9 ete can say of front makes achoro to tls abstraction of a goneric mo! rroal at all mobile phones from different manufacturers are nothing Pu differen abstraction of a generic mobile phone. Inheritance Inheritance is the process by which objects of ond tlass acquire the properties of objects of another class. Inheritance supports the concept Ol or rarenicar-classiication™. For example, the bird robin is @ part of the class flying bird, which is again a part of the class bird. As illustrated in Fig. 1.4, the principle behind this sort of division is that each derived class ‘Shares common characteristics with the class from which it is derived. ritance provides the idea of reusability. This means that we can add deriving a new class In OOP, the concept of inhe! ‘additional features to an existing class without modifying it. This is possible by from the existing one. The new class will have the vonbined features of both the classes. Thus the real appeal and power of the inheritance mechanism ie that it allows the programmer fo reuse a class what he wants, and 10 tailor the class in such @ way that it does not that is almost, but not exactly, Attributes: Feathers Lay eggs Nonflying Penguin Kiwi Robin ‘Swallow | Attributes: ibutes: utes: Attributes: Attributes: Attributes: ERY Property inheritance ‘Scanned with CamScanner Fundamentals of Object-Oriented Programming 5 vrrpuelaeey UNd®SIeabIo so eflects Into the rest ofthe classes. In Java, the derived class Is known as ‘subolage’ meena eth Subctaas defines only those fectures thal ate unique fo K. Without the use of Inhertance, each class would have to explicitly include all ofits features. Polymorphism Polymorphism is an Gaiden Cae, An porton ay oi of addition, For tgs Pot he typos of data used in the ‘ope operation would progr et: the oporalion will generate a-sunhc I the operands are strings, then the name can be uso 10 hacia string by concatenation. Figure 1.8 illustrates that a ‘single function similar 10 © particular word naw erent Number and different types of arguments. This is something “ord having soveral dtferant meanings depending on the content, a Circle Object, Box Object Triangle Object Draw (Circley Draw (box) Draw (Triangle) EERE Poiymorpnism Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. This means that © general class of operations may be accessed in the same manner even though specific actions associated m e with each operation may differ. Polymorphism is extensively used in implementing inhetiiance ompile Time and Runtime Mechanisms . /in the context of a Programming language, compile time may refer to any of the following: +The operations performed by the compiler such as syntactic and semantic analysis + The pre-runtime assessment of the program's behavior In Java, apart from syntax and semantic checks, one important logical task that is considered to be Performed at compile time is the implementation of inheritance. Itis at compile time that the child class inherits the public data members and methods of the base class, Runtime, on the other hand, is the time period when a syntactically correct program is actually executed in the computer system. Thus, all the tasks that are performed during this time petiod are prefixed with the word ‘runtime’ or ‘dynamic’, such as runtime type checking or dynamic memory i ated with runtime is the implementation allocation. In Java, one of the important concepts that is associat of polymorphism. It is also referred as dynamic binding, as explained in the next section, Dynamic Binding in to the call. i inking of a procedure call to the code to be executed in response D Dynan binding sane that the’ code associated with a given procedure call is not known until y ‘Scanned with CamScanner 8 Programming with Java the time of the call at runtime. Its associated with polymorphism and inheritance. A procedure call sssociated with a polymorphic reference depends on the dynamic type of that reference. Consider the procedure "draw" in Fig. 1.5. By inheritance, every object will have this procel ire algorithm is, however, unique to each object and so the draw procedure will be redefined i" ake ‘that defines the object. At runtime, the code matching the object under current reference Message Communication each other. The AAn object-oriented program consists of a set of objacts that communicate th acpasic tops Process of programming in an object-oriented language, therefore, involves: 1, Creating classes that define objects and their behavior. 2. Creating objects from class definitions. 3. Establishing communication among objects. a a much the same Odjects communicate with one another by sending and receiving information mt of mescage way 8 people pass messages to one another as shown in Fig. 16 The I neie real-world passing makes it easier to talk about building systems that directly mo counterparts. Object 4 Care | Object 2 \ Gms) Object 3 Network of objects communicating between them A message for an object is a request for execution of a procedure, and therefore will invoke a method (procedure) in the receiving object that generates the desired result, as shown in Fig. 1.7. Sendir Object 2. Method () ) Rese Object Message triggers a method ‘Scanned with CamScanner Fundamentals of Objoct-Orlonted Programming 1 dhe er 8 Invotve i thd (mes: ord the intormaton® specifying the name of the object, the name of the mothod (1 vu 10 Be Sent. For example, consider the statement saga) H Empl poeeelar (name jere, Em : information, °° 'S the object, salary is the mossago ond namo Is tho parameter that contains Employee.salary (name! coin __| | Message Information Objects have a life feasible as long as it ie ae They can be created and destroyed. Communication with an object is 14 BENEFITS OF oop ‘ Wren inhertance, we can eliminate redundant code an iid Programs from the standard worki Neate wit rather than having to start writing gr prrking Modules that communicate with one anther, é 1e cod it time and tigher osu le from scratch. This leads to saving of development 3. The principle of data hiding helps the invaded by 2050 ano, propresiammer to bull secure programs that cannot be 'tis possible to have multiple objects to eo Possible to map objects in the problem dor Itis easy to partition the work in a project bas The data-centered design approach enable: implementable form. Object-oriented systems can be easil | Message passing techniques for communication between objects, “ake the interface descriptions with external systems much simpler. 10. Software complexity can be easily managed. While itis possible to incorporate all these features in an objectoriented system, their importance depends on the type of the project and the preference of the programmer. There are @ nember af issues that need to be tackled to reap some of the benefits stated above. For instance. class libraries must be available for reuse. The technology is still developing and current products may be superseded quickly. Strict controls and protocols need to be developed if reuse is not to by compromised. : - A software that is easy to use is hard fo build. It is hoped that the objectoriented programming languages like C++ and Java would help manage this problem. \d extend the use of existing classes, without any interference. main to those objects in the program, ed on objects. SUS to capture more details of a model in an Noe oe ly upgraded from small to large systems. 1.5 APPLICATIONS OF OOP is ramming buzzwords today. There appears to be a great deal of excitement ond sat ion semare engineers in using OOP. Applications of OOP are beginning to gain ‘Scanned with CamScanner KEY TERMS Oak | Internet | World Wide Web | Applets | Package | Platform-neutral | Mulithread | Bytecode | Pynamic linking | Native methods 1 HTML | Web browser | Applet tag | Web server | HotJava | Netscape Navigator | appletviewer | java | javac | javap | javah | javadoc | jdb 2.1 JAVA HISTORY URz IS 2 general purpose, objectoriented programming language developed by Sun Micros stems USA in 1981. Originally called Oak by James Gosling, one of the inventors of the language, Java was ‘esigned for tie development of software for consumer electronic deviees ike TVs, VCRs, toasters and Such other electronic machines. The goal had a strong impact on the d ‘development team to make the ‘enguage simple, portable and highly reliable. The Java team which included Patricle Naughton discovered that the existing languages like C and C++ ms limitations in terms of both reliability and Portability. However, they modeled their new languageava)on Cand C++ but removed a number of features of C and C++ thal were considered as sources Of problems and thus made Jova 4 really simple, reliable, Ponable, and powerful language. Table 2.1 lists some important milestones in the development of Java. Table 2.1 Java Milestones f Year _ Development | "940 | Sun licosystems decided to develop special sofware that could be used W manipulate consumer Gleaonic devices. A team of Sun Microsystems programmene heasea by James Gosling was formed to undertake this task 1291 | Alter exploring the possibilty of using the most popular object-oriented language C++, the team announced a new language named "Oak The team, known 2s Green Project team by Sun, demonstrated the application of their new language to Conlvol ist of home appliances using a handheld dovice with a liv echoesclnee seen 1993 | The World Wide Web (WWW) appeared onthe Intemet and transformed the text-based Internet into a Srephicalrich environment. The Green Project team came Up with the idea of developing Web applets (tiny Propreme) using the new language that could run on all types of computers connected tolnternet 1992 (Conta) ‘Scanned with CamScanner = 12 Programming with Java Compiled and Interpreted Usually « computor language Is either compiled or interproted. Java combines both these approaches thus making Java a two-stage system, First, Java compitor translates source code into what is known 1s bytecode instructions. Bytecodes aro not machino instructions and therefore, in the second stage, Java intorproter gonorates machine code that can be directly ‘executed by the machine that Is running tho Java program, Wo can thus say that Java is both a compiled and an interpreted language. ple and Porta Platform-Independen| Tho most significant contribution of Java over other languages Is its portability. Java programs can be easily moved from one computer system to another, anywhere and anytime. Changes and upgrades in operating systoms, processors and systom resources will not forco any changes in Java programs. This is the reason why Java has become a popular language for programming on Internet Which intorconnects different kinds of systems worldwide. We can download a Java applet from a romote computer onto our local system via Intornot and execute it locally. This makes the Internet an extonsion of the user's basic system providing practically unlimited. number of accessible applets and applications. ; Java ensures portability in two ways. First, Java compiler generates bytecode instructions that can be implemented on any machine. Secondly, the sizo of tho primitive data types are machine- independent. Object-O Java is a true object-oriented language. Almost everything in Java Is an object. All program code and data reside within objects and classes. Java comes with an extensive set of classes, arranged in packages, that we can uso In our programs by inheritance. The object model in Java Is simple and easy to oxtend, nted Robust and Secu Java is a robust languago. It provides many safeguards to ensure reliable code, It has strict compile timo and run timo checking for data typos. It is dosigned as a garbage-collected language relieving the programmers virtually all memory managoment problems. Java also incorporates the concept of exception handling which captures serious errors and climinates any risk of crashing the system. Security becomes an important issue for a language that is used for programming on Internet. ‘Threat of viruses and abuso of resources aro everywhere, Java systems not only verify all memory recess bul also ensure that no viruses aro communicated with an applet. The absence of pointers in Java ensures thal programs cannot gain access to memory locations without proper authorization, Distributed Jay 's designed as a distributed languago for croating applications on networks. It has the ability to share both data and programs. Java applications can open and access remote objects on Internet ‘as easily ax they can do in a local system, This enables multiple programmers at multiple remote ‘ocations to collaborate and work togothor on a singlo project, Simple, Small and Familiar Java is a small and simple languago, Many features of C and C++ that are either redundant of sources of unreliable code are not part of Java. For example, Java does not use pointers, proprocessor header filos, goto statomont and many others, It al Iso eliminates operator overloadin and muttiplo inhoritance, For moro dotalled comparison of Java with C and C++, ‘olor to Section 2.3, : ‘Scanned with CamScanner ry Java Evolution 13 Fovitarity . Se aecing feature of Java. To make the language look familiar to the existing Fore, Java code “oem C-aNd C## languages. Java uses many constructs of C and C++ and therefore, © “Tooks like a C++" code. In fact, Java is a simplified version of C++. multithreaded and Interactive muttthreaded means banding multiple tasks simultaneously. Java supports multithreaded Foe ee i name, nat We need not wait for the application to finish one task before beginning another. For exam! alet Ten listen to an audio clip while scrolling a page and at the same time download an applet from a distant computer. This feature greally improves the interactive performance of graphical applications. The Java runtime comes with tools that support multiprocess synchronization and construct smoothly running interactive systems, High Performance Java performance is impressive for an interpreted language, mainly due to the use of intermediate bytecode. According to Sun, Java speed is comparable to the native C/C++. Java architecture is also designed to reduce overheads during runtime. Further, the incorporation of multireading enhances the overall execution speed of Java programs. Dynamic and Extensible Java is a dynamic language. Java is capable of dynamically linking in new class libraries, methods, and objects. Java can also determine the type of class through a query, making it possible to either dynamically link or abort the program, depending on the response. " Java programs support functions written in other languages such as C and C++. These functions are known as native methods. This facility enables the programmers to use the efficient functions available in these languages. Native methods are linked dynamically at runtime. Ease of Development Java 2 Standard Edition (J2SE) 5.0 supports features, such as Generics, Enhanced for Loop, Autoboxing or unboxing, Typesafe Enums, Varargs, Static import and Annotation. These features reduce the work of the programmer by shifting the responsibility of creating the reusable code to the compiler. The resulting source code is free from bugs because the errors made by the compiler are less when compared to those made by programmers. Thus, each of the linguistic features is designed to develop Java programs in an easier way. Scalability and Performance J2SE 5.0 assures a significant increase in scalability and performance by improving the startup time and reducing the amount of memory used in Java 2 runtime environment. For example, the introduction of the class, data sharing in the Hotspot Java Virtual Machine (JVM) improves the startup time by loading the core classes from the jar files into a shared archive. Memory utilization is reduced by sharing data in the shared archive among multiple JVM processes. In the earlier versions, the data was replicated in each JVM instance. Monitoring and Manageability Java supports a number of APIs, such as JVM Monitoring and Management API, Sun Management Platform Extension, Logging, Monitoring and Management Interface, and Java Management Extension (JMX) to monitor and manage Java applications, For example, Java provides JVM Monitoring and Management AP! to track the information at the application level and JVM level when ‘Scanned with CamScanner vava Evolution 15 + Aammenge Eeencnementa: tava SET atts severa! language features aimed at helping the SHSNes Ne SUE finctonaety with ease The new language features include nue AETANHON hanfing, dhamond syntax, ete Y (NWO 2.0) to Java SE 7 makes it a lot easier to work with file nS SOME EanoEMEN uch as open, read, Aows the programmers to create custom file systems tes parallel programming through the use of Fork/Join reacted programming allowed programmers to use a ee EES ‘Xo framework enables programmers to make the Des ese oF he avaniadio Mumle processors through parallel programming, > Dyoere Lenpoage Support: Java SE 7 supports dynamically typed languages in the JVM. THE _Heoteeymamc Instruction §& used to dofine customized linkage mechanisms for these RRINTS IS NOW JAVA DIFFERS FROM C AND C++ SiPEETY EAS wes Maooles ster C and C++ languages, it differs from C and C++ in many ways. gee OES NOE SOTO g Number of features available in C and C++, For the benefit of C and C++ FOTOS. we DOM out Here S few major Gierences between C/C++ and Java languages. ee ee owe S = Lt Hee C St The major Gifference between Java and C is that Java is an object-oriented mxgueee anc hss mechenism f define classes and objects. In an effort to build a simple and safe ierguape. De eve team cid not include some of the C features in Java. love Goss Not NaUTE the C unique statement keywords sizeof, and typedef. eee Goes Net contain the date types struct and union. eve GOSS NOt Sefine the ype modifiers Keywords auto, extern, register, signed, and unsigned. 4. Jeve Odes not support an explict pointer type. 5. lieve Goss not have = preprocessor end therefore we cannot use # define, # include, and # Sef ssements, : = Jove requires thst the functions with no arguments must be declared with empty parenthesis End not with the void keyword as done in C. 7. Jeve sods new operstors such ex{instanceof and >>>>-2- Jove 20ds isbeled break and continue statements. Jaws ads many festures required for object-oriented programming. and C++ ‘we object-oriented language while C++ is basically C with object-oriented extension. That. not exactly the Increment operator ++ indicates. C++ has maintained backward compatibility with is Therefore possibile to write an old style C program and run it successfully under C++. Java appears to be similar to C++ when we consider only the “extension” part of C++. However, some cnyect-onecied features of C++ make the C++ code extremely difficult to follow and maintain. “Listes below ere some major C++ features that were intentionally omitted from Java or significantly modifies. 1. Jaws does not support operator. ‘overloading, 2 Jave does not have template classes as in C++. Jave does not Support multiple inheritance of classes, This is accomplished using a new feature calied “interface”. Cee ‘Scanned with CamScanner 16 Programming with Java 4. Java does not support i global variables, Ever variable and method is declat it nf red with and forms part of that class. "in a class 5. Java does not use pointers. 6. Jaya-has replaced the finalize) tune) eee non h 7. THeTETTE no Reader files in Java. __ Java also adds some new features. While C++ is @ superset of C, Java is neither a superset nor a subset of C or C++. Java may be considered as a first cousin of C++ and a second cousin of C as. illustrated in Fig. 2.1. A more detailed discussion on the differences between C++ and Java is available in Appendix A. Fig EI) Overlapping of C, C++, and Java 2.4 JAVA AND INTERNET Java is strongly associated with the Internet because of the fact that the first application program written in Java was HotJava, a Web browser to run applets on Internet. Internet users can use Java to create applet programs and run them locally using a “Java-enabled browser” such as HotJava. They can also use a Java-enabled browser to download an applet located on a computer anywhere in the Internet and run it on his local computer (see Fig. 2.2). In fact, Java applets have made the Internet a true extension of the storage system of the local computer. Internet users can also set up their Web sites containing Java applets that could be used by other remote users of Internet. The ability of Java applets to hitch a ride on the Information Superhighway has made Java a unique programming language for the Internet. In fact, due to this, Java is popularly known as Intemet language. Remote [—— Computer ——— Internet Remote == SExy Local Computer GRA] Downloading of applets via internet ‘Scanned with CamScanner Java Evolution 17 2.5 JAVAAND WORLD WIDE WEB World Wide Web (WWW) is an open-ended information retrieval system designed to be used in the Intemet's distributed environment. This ( system contains what are known as Web pagos: ‘ that provide both information and controls. Unlike = \w ( a menu-driven system where wo aro guided " though a particular direction using a decision troo ae structure, the Web system is open-ended and we — = can navigate to a new document in any direction ‘as shown in Fig, 2.3. This is mado possible with oan —— the help of a language called Hypertext Markup . Language (HTML). Web pages contain HTML (ERE Won structure of information search tags that enable us to find, retrieve, manipulate and display documents worldwide. Java was meant to be used in distributed environments such as Internet. Since, both the Web and Java share the same philosophy, Java could be easily incorporated into the Web system, Before Java, the World Wide Web was limited to the display of still mages and texts. However, the incorporation of Java into Web pages has made it capable of supporting animation, graphics, games, and a wide range of special effects. With the support of Java, the Web has become more interactive and dynamic On the other hand. with the support of Web, we can run a Java program on someone else's computer across the Internet, Yava communicates with a Web page through a special tag called . Figure 2.4 illustrates this process. The figure shows the following communication steps: User's Computer Remote Computer Bytecode Applet Source o Code { ' Java HTML Bytecode Web Sao Document 1 ‘Applet Tag Request HTML Document Output Web Server (EEG) Love's interaction with the web ‘Scanned with CamScanner 18 Programming with Java 1. Tho user sends a request for an HTML document to the remote computer's Web server. The Web server is a program that accepts a request, processes the request, and sends the required document. 2. The HTML document is returned to tho user's browser. The document contains the APPLET tag, which identifies the applet 3. The corresponding applet bytecode is transferred to the user's computer. This bytecode had A ae Previously created by the Java compiler using the Java source code file for that applet. Te {javarenabled browsor on tho user's computer interprets the bytecodes and provides 5. The user may havo further interaction with the applet but with no further downloading from the Provider's Web server. This is because the bytecode contains all the information necessary to interpret the applet. 2.6 WEB BROWSERS As pointed out earlier, the Internet is a vast sea of information represented in many formats and stored ‘on many computers. A large portion of the Intemet is organized as the World Wide Web which uses hypertext. Web browsers are used to navigate through the information found on the net. They allow Us to retrieve the information spread across the Internet and display it using the hypertext markup language (HTML). Examples of Web browsers, among others, include: 1. Hotava 2. Netscape Navigator 3. Internet Explorer HTML documents and tags are discussed in detail in Chapter 14. HotJava HotJava is the Web browser from Sun Microsystems that enables the display of interactive content ‘on the Web, using the Java language. HotJava is written entirely in Java and demonstrates the capabilities of the Java programming language. ‘When the Java language was first developed and ported to the Internet, no browsers were available that could run Java applets. Although we can view a Web page that includes Java applets with a regular browser, we will not gain any of Java's benefits. So far as being a Web browser goes, it is nothing special and does not offer anything special that most other Web browsers don't offer. Its biggest draw is that it was the first Web browser to provide support for the Java language, thus making the Web more dynamic and interactive. HotJava has been discontinued by Sun and is no longer available now. Netscape Navigator Netscape Navigator, from Netscape Communications Corporation, is a general-purpose browser that can run Java applets. With versions available for Windows, Solaris and Apple Macintosh, Netscape igator was one of the most widely used browsers of its time. But with increasing popularity of jet Explorer browser, the use of Netscape Navigator decreased over a period of time. Even pe communications has stopped further development of this browser after its last stable release in March 2008. rnet Explorer jet Explorer is another popular browser developed by Microsoft for Windows 95, NT and XP tations. Both the Navigator and Explorer use tool bars, icons, menus and dialog boxes for navigation. Explorer uses a just-in-time (JIT) compiler which greatly increases the speed of cution. ‘Scanned with CamScanner Java Evolution 19 2.7. HARDWARE AND S¢ WARE REQUIREMENTS, Java is supported across multiple operating systems such as Sun Sol Windows Server operating systems, Windows Vista, Windows 7 and of Java are Java SE 6 and Java SE 7, Some of the typical hardware ani Red Hat Enterprise Linux, \dows 8. The latest versions \, id s¢ ‘java SE 6 are listed in Table 2.2. jofware requirements for Table 2.2. System Requirements for Java 6 Platform - Memory _ Browsers Disk Space Solaris SPARC 82-bit 64MB | Mozilla 1.4 or above ‘32-bit install, 65 MB {Solaris 10) ca Windows Intel Architecture 32-bit 64MB Firefox 1.06 or above, 98 MB {Windows XP Professional, Win 2000 professional) IE 6.0 or above Windows Intel Architecture 32-bit 128 MB Firefox 1.06 or above, 98MB (Windows Server 2003 and Windows Vista) IE 6.0 or above Windows Intel Architecture 64-bit 128 MB 64-bit OS, 32-bit JRE, 110 MB {Windows XP Professional, Windows Server 2003, 1E.6.0 or above Windows Vista) Linux 32-bit 64MB Mozilla 1.4 or above 58 MB (Red Hat 9.0, Red Hat 2.1, Suse Enterprise Linux Server 9) Linux 64-bit, 64 MB 64-bit OS, 32-bit JRE. 56 MB (Guse Enterprise Linux Server 9, Red Hat Mola 14 or above Enterprise 3.0) ‘Source: Sun Microsystems An editor (like notepad) is required for writing programs in Java. However, a number of IDEs are also available for developing java code. These IDEs allow the users to write, compile, and execute Java programs from a single interface. Some of the popular Java IDEs are Eclipse, Jcreator, Jooder and Netbeans etc. 2.8 JAVA SUPPORT SYSTEMS Itis clear from the discussion we had up to now that the operation of Java and Java-enabled browsers on the Internet requires a variety of support systems. Table 2.3 lists the systems necessary to support Java for delivering information on the Internet. Table 2.3 Java Support Systems ‘Support System Description internet Connection | Local computer should be connected to the Internet. Web Server ‘A program that accepts requests for information and sends the required documents. Web Browser ‘Aprogram that provides access to WWW and runs Java applets. HTML A language for creating hypertext for the Web. APPLET Tag For placing Java applets in HTML document. Java Code Java code is used for defining Java applets. (Conta.) ‘Scanned with CamScanner Tae APPLET og ad varsoed othe wer compu. ee T From Sever | Anitarmadate seer etme te requestry co wrtsttn angi ina eve ‘ppcay mptemennd emg toy ; aa Senet ‘cout syste Bat states chang (senna ecehing) ecko ma os8 2.9 JAVAENVIRONMENT Jova envranment ines a re nme of doveopment ols and une of dassas and methods, ‘he overt tse pt be sjte raw a va Dovopnet Ki OK) ond tho Sassos Zuimedose oe pat ol ano Sunaid Lary JS). aso knw a he Appt Programming Inetace (AP) Java Development Kit ‘The Java Development Kt comes with a collection of feos that aro used for developing and running Java programs They cide: appletvewer (foe wowing Java applets) favac (Java complet) fava (ava error) fava (Java esassombler) Javan (or C header es) Javadoc (or creating HTAL documents) + sb ava debugger) Table 24 tat thee tools and thee descriptions. ‘raies ws 5 Jaap ito acaly ving alo conpato Bowe overt whch as aplesanappicatons ty ready anditepretng lees tes ‘rw Jva cone. whch Varsaes Java sourcecode yleade es Mat he wlepetr can Crates HT. Aoma cocaine sure cae es, Prosices header tes we at rave mes Joa assent ch enables so cme yea es i a program desrpon, acting ch ness eros not OgFAMS Tho way ese tos apd obs and in appeaton progam is usted in Fig. 25. To crate Ja poy we fod eae cea code wg we war Te sou Eos is then comple wang the Java compte fvae ad ened use be Jove lee oa, he Java debugger eb seed ond errs, ay. he soe cade &compled ava progeanson oe converted ino a sours eae win Bw hl of lvadeassenbeJvap, Wo eam more aoe eee 10018 a we work through the book. in a seas the att é 4 Econ application Programming Interface : “es 10 Java Standard Library (or API) includes Lo) aadeg Tro ai ay ane ‘Text Editor ea ey Treads of classes and motheds grouped ia Ifotal functional packages (soo Append B) : Aateommonty used packages ae: 1. Language Support Package: A cotecton fof asses and methods requred for Eno, maning bas features of Java 2. Uililes Package: A covecton of classes to prowdo vty Tunchons such as date and to fonctons 3 InpwWOutput Package: A cotecton of classes required for inpuwougat manu 44, Networking Package: A cotecton of class fs for communicating with ether computers a Intomet. 5, AWT Package: The Abstract Window Too! Kit packago contains classes that implo- ments plaformindependent graphical user Interface, 6, Applet Package: This inciudes 2 set of classes that allows us to create Java ap- plats. “Thowse ofthese library cases will become evident when we tart developing as programs, Java Runtime Environment ‘Tho Java Runtime Environment (JRE) facitates the executon of programs developed in Java. It primary comprises the following: 4, Java Virtual Machine (JVM): It is a program that intrpets the intermediate Java byte code ‘and generates the desired output. I is because of byte cade and JVM concepts that programs waite in Java ar highly portable. 2, Runtime class libraries: These are a set of core class libraries that are required for the ‘execution of Java programs. 23, User Interface toolkits: AWWT and Swing are examples of toolkits that support vared input methods forthe users to interact with tho appicaten program. 4, Deployment technologies: JRE comprises tho folowing key deployment technologies: (a) Java plugen: Enabos the execution ofa Java applet on tha browser. {b) Java Web Start: Enables remoto-deployment of an application. With Web Start, users can iaunch an application directly from te Web browser without going through the instalation procedure. SUMMARY In this chapter, we have introduced a bret history of Java and its salient features. Java is a pure-object-orented language inoduced by Sun Mrosystems of USA and has a number of Charactersts that make it suitable for Interet programming, We have discussed briefy how Java an be incorporated Into the World Wide Web system with the help of Web browsers. ‘Scanned with CamScanner Overview of Java Language main | public | stale | vold | string | args | printin | double | Math | sat I package | | | Tokens | Literals | Operators | Soparators | Unicode | Keyword | Statement ) | Command Line Argumonts | Frooform | Classos and their relationships tion | Composition | Realization | UML Notations © ggss | Identifier In import | Interfaco Virtual Machine | Iortanco | Association | Aggroga 34 INTRODUCTION Java is a general-purpose, object-oriented programmin programs: 1. Standalone applications 2, Wob applots Thoy are implomented as shown in Fig. 3.1, Standalone applications are prosren written in Java to carry oul certain tasks on a standalone local computer. In fact Java can be used ‘to develop programs forall kinds of applications, which ealler, were developed using languages like C and C++. Re pointed out earlier, HoWJava itso is a Java application program. Executing @ standalone Java ‘program involves two steps: 4. Compiling source code into bytecode using javac compiler. 2. Executing the bytecode program using Java interpreter. ‘Applets are small Java programs developed for Internet applications, An applet locator on 2 distant computer (Server) can be downloaded via Internet and executed on a local computer (Client) using a Java-capable browser. We can develop applets for doing everything from simple animated graphics to ‘complex games and utilities. Since applets are embedded in an HTML (Hypertext Markup Language) Goecment and run inside a Web page, creating and running applets are more complex than creating ‘an application, Standalone programs can read and write files and perform certain operations that applets cannot do. An applet can only run within a Web browser. In this chapter, we shall consider some simple application programs, which would demonstrate the genera stucture of Java application programs. We shal also discuss here the basic elements of vava language and steps involved In executing a Java application program. Creation of applets will be discussed later in Chapter 14. 19 language. We can develop two types of Java ‘Scanned with CamScanner cise] 3.2. SIMPLETAVA PRoGRAM The best way to lea a new ln 2109 sowie afew sip exampleprogtams and execute ther ‘We begin with a very simple pr ve ee Moree rogram that prints ane of text as ouput Program 3.4 © Semplecne Fobiie statie veld nate etring argel ’ Program 31 is prhaps ne 8 he snpest oa Java features of the tar Thuebte dn Class Declaratio The fist ine Overnew of Jaa Language 25 declares 8 class, which fs an objectoriented construct. As stated earlier, Java is a wwe tanguage and therelore, everything must be placed inside a aod coe class. class is a keyword and ded 3 a now class definition folows, SamplaOne isa Java identfr that specs tre close wetanen ph ava i Specifies the name ofthe clase Opening Brace very 088 defi in Java bogie with an opening race and ends witha sppocting i the lst kno in tho example. This fs ma fo C+ clas co matching losing brace“, Golintion in C++ ends with a semicolon) ns it a 8 Cane wet ie OE cette The Main Line 4 ‘The third line y ae etines 9 method named main. Conceplaly, his is simiar tothe main{) function in CIG+. Every Sava application program must inlude th main) method. This i te staring pont forthe iirpetee {S-bagin the execution of the program. A Java application-can have any number of classes but ‘one of them must include’ a main method to initiate the execution. (Note that Java applets will nol use the main method at al.) - ee imber of keywords, public, static and void. The Keyword public ls an acces specifier that declares the main sethod” as unprotected and therefore making it accessible to all other classes. This is similar to the Crt public modi fier. Geatic: |Next appears the keyword atatic, which declares this method a5 one that belongs to the eftire class and not a part of any objects of the class. The main must always be declared Gs static Gince the interpreter vees thie method before ny objects are created. Nore about statie methods and| variables will be discussed latec in Chapter 3. ‘The type modifier void states that the main method does not return any value (but simply prints sone text to the screen.) Void ‘Al parameters to a method are declared inside a pair of parentheses. Hore, String args{ ] declares 1 parameter named args, which contains an array of ebjects ofthe classtype String. The Output Line “Tne only executable statement inthe program is ‘This is simitar tothe print) statement of C or cout << construct of C++, Since Java is a true object tented language, every method must be part of an object. The printin method is a member of the ‘out object, which i a static data member of System class. This line prints the string {othe screen. The method printin always appends @ newine character to the end of the string. This means that any subsequent output wil start on a new lie. Note the semicolon at the end of the statement. Every Java statomont must end with a semicolon, (Saving, compiling, and executing 2 Java program are discussed in Section 3.8) ‘Scanned with CamScanner "9 Wath Jo 8 Momeorias ei Mi a a an PePlte static void maine, ' Poinisteing args 11 Bechoration and seit tatization Printin (ry ae ) Yoon 3 datatype used to voprosane hapten). The statement °/PeHent Rees ha mead sao the Math ccs, con Sern The an A Mt a pee aa ‘splays the resut onthe screen os Note the uso of + symbol. Here, °F Is converted into asin representation casa Use of Math Functions "Noto tat hott statoment in he pop is Corina h ine verse yo ce at 8 Mat aoe Wn pe gnu OA Soe nC. Pamertat, Math dean Gatacs bs aot wien cerns wishin Ce Ten deepen esa eon ee Snes codeing x a ¥. For by Sang WsaP wea eit We 8 too cont 0" 8 tn ord A = vn me CES ‘we a. fesse th HO ott OO UG a LASSES = icaTion WITH TWO CL fiat conidiad Oe sees ene Sater AN APPLIC en dais @ Sais BySCBiCn, Wes we 34 cet Be dase. PICO 3 oh be ay (0 ghee oases agen heen hase Pom at tengthy oat 30 a peeadtby erate Progam 33 ctines to dasses Room and RoomArea. The Room class defines two sr rad aso vasa ee vals The ae Reamavescatane te mais hee ne main method decares local variable area and a Room type object room! nd then assign ‘ives lo te data members of Room class by using the getdata method. Finaly, it clauates th ‘Scanned with CamScanner ‘ea and pnts theres 28s. Classes and later inthis Chapter. ts. Note the use of dot cperatr to access the vi arabes and methods of ‘methods are ciscussed in Chapter 8. The use ot fae the Keyword ne is exponent 3.5 JAVA PROGRAM STRUCTURE AS we hav seen in the previous examples, Java progam ma sf mathe. Classes crt ta members and methods tha operate a ass thas may conan data ype dedaatont and excels taor To wnte a Java program, fe oe ne pee we fet define classes and then put thom fopethor A lava pogo ‘contain one or more sections as shown in Fig 32. - aaa contin many castes of which ony Donumeriaton Seton —— sengeses Postage Street - oxen Inport Satenents onteat ‘Intertace Statements | ———— Optiona (Sse etntans omens J Monten Gass front betntan Essen ———____] General sects ofa. Jva rogram Documentation Section Package St atement The frst statement allowed in a Java file is a package slatoment This statement declares @ Package name and informs the compiler that the classes defined here belong to Wis package Example: ‘The package statement is optional. Thats, or classes do not have to be part of package, More about packages willbe discussed in Chapter 11, veri of Jove Language 22 ements fore any class definitions) may be a number of ort statem 19 statement (but before any vr ping ater 2 POC OT ater in. Example ‘ott pont tater f load the test class contained in te package student. somentinstusts.tna.inlereses lasses that are pat of other named packages. More statements: larations. This is also an optio e Statcrne NT gut incdes a group of method declarations. This is also an optional Seen ein en eg et nee new eonceh ition mary and essential Definitions ‘dase definitions. Classes are the primary and Css Maram ray conta mute ats Ses iets rearward prblome The ‘amen’ of 21348 BOG. tne comply ofthe problem. yer a asses US Main Method Class va st fequites a main method as its stating point, this clas is the ‘ava standalone program requt Jn method a its stating poi ‘nce every Java standalone pra java program Thay contain only this part. The main rethod csr prof va progam, Rapes StF communications between ther. On reaching ie ces 6c a ee and te contol passes back he operating system at man the rogram fe 7 ava TOKENS _. se basically a collection of classes. A class is defined by a set of a ee 1d containing executable statements (see Fig. 3.3). Most statemer statements and eno es so the actions cartied out on data, Smallest individual units in a program are ere ening permeated Saco ie et Cha crn wae ce. cami ose ape i iam ie ion Java Character Set ‘Tho smalestunts of Java language are the characters used to write Java tokens, These characters a defines by the Unicode character set, an emerging standard that tres to create characters for 2 lage eumber o scripts worldwide, ‘The Unicode is 16-bit character coding system and currently supports more than 34,000 defined ‘faeces derived from 28 languages from America, Europe, Middle East, Arica and Asia (ineluding India). However. most of us uso only the basic ASCII characters, which include lellers, digs and creeet ar Carats. Used in normal English. We, therefore, have used only ASCII character set (a ‘beet of UNICODE character se in developing the programs in this book ‘Scanned with CamScanner r 30 Programming with Java Tokens ears . - Jaration statemen ables | J ™ Section | Declaration statement Tokens Method 1 I A eroressons ana + ‘Statements Tokens snes lethods Method 2 baa Elements of Java class Keywords However, itis a bad practice and should be avoided Identifiers Identifiers are programmer-designed tokens, They are used for naming classes, methods, variables, objects, labels, packages and interfaces in a Program. Java identifiers follow the following rules: J. They can have alphabets, digits, and the underscore and dollar sign characters, 2. They must not begin with a digit, 3. Uppercase and lowercase letters are distinct, 4. They can be of any length. ‘Scanned with CamScanner Su be remembered that HONS AS Long as We oo 1 fese ae comentons and not es. Aad ot es. We may ftw ‘Hot brmak the basic rules of naning kentifiers. mY Fo OF om Users 6 Jove are mt vane ain, 8 SENN ot characters (89Hs, eters, and other cha tise he, a roctos) that “ see stored in variables. ‘tava language specifies following types of iterals: a + Fisetng port ters + Character erate + Sep ters Operators Ao cperator is a syria! that takes one or more (Operators are ot many nee ont eo Me arguments and operates on them to prodhce 8 result Separators Secartors are symbols sed to s fScate where groups of cade ae died and aa -sSsaty Sefne te she an tncton of ou ease Table 32a sanorats es ee Overvew of Java Language 22 De ern pereneten Wed cent nd nan aia we SS lemon essa, cong eoracrs Btw coe on senaeeee ape — SSE SRLS tty escarole alot oteae tr (eee Steere eee aren | ees sepowt caterers — Lae erate coment etten heart cs ersten Remus | oe ectron st do it aon — | \opetier nite a to satameet en piv Suienent” | Thee onc andere used ung program devise | Some as Cand G pers se sera pactge names fo a page nl sea ad a sp 8 sapiens . a mint sutment | Aystimert ny oeonwn ait! Suctaes st | Mere pC ards {ckoenesn tay Second atanvansbenot | ecptne se Teaincrutcrenncsus hanesewedse | Somers 7 JAVA STATEMENTS SScprrnneramo eens wach Se The statements in Java are the sentences in natural languages. A satement& an execute sin tenn | it sents oe eet seers same asc combination of tokens ending wih a semicolon (:') mark. Statements fe unuly exceed ‘peter eesdeaannscr sequence in the order in which they appear. However, te posse to conte! te ow of eacuson en re reener Pre Decent, Ps: \C necessary, using specal statements Java implements several ypes of saements os sted ‘Sten en nrmer Mts Cnn Acton in Fig. 3:4 and Gesenbed in Table 33. They are consiered iv Gopth a and when thoy a Soe encountered ‘coy Ee ‘Scanned with CamScanner

You might also like