Evolution of Object Approach: C Programming Language
Evolution of Object Approach: C Programming Language
Classes
Class is defined as an abstract data type characterized by a set of properties (attributes
and functions) common to its objects. Objects of the same nature, for example
employees of a company, will generally have the same structure and the same
behavior. Hence we create class. The class expresses the common features and
constitutes a means of classification. The entire set of data and code of an object can
be made a user-defined data type with the help of a class.
In fact, the objects are the variables of type class. Once a class has been defined, we
can create any number of objects belonging to that class. This is called instantiation.
Each object is associated with the data of type class with which they are created. A
class is thus a collection of objects of similar type. For example, mango, apple, and
banana are members of the class fruit. Classes are the user-defined data type and
behave like the built-in types of a programming language. The syntax used to create
an object is no different than the syntax used to create an integer object in C. If fruit
has been defined as a class, then the statement fruit mango; will create an object
mango belonging to the class fruit.
Data Abstraction
“An abstraction denotes the essential characteristics of an object that distinguish it
from all other kinds of objects and thus provide crisply defined boundaries.”
It focuses on the outside view of an object. Abstraction refers to the act of
representing essential features without including the background details or
explanations. Classes use concept of abstraction and are defined as a list of abstract
attributes such as size, weight, cost, and function to operate on these attributes. They
encapsulate all the essential properties of the objects that are to be created. Since the
classes use the concept of data abstraction, they are known as Abstract Data Types.
Encapsulation
The fundamental idea behind object-oriented approach is to combine both, the data
and the functions that operate on that data, into a single unit. The wrapping up of data
and functions into a single unit (called class) is known as encapsulation. Data
encapsulation is the most striking feature of a class. Here, the data is not accessible to
the outside world and only those functions which are wrapped in the class, called
member functions, can access it. These member functions provide the interface
between the object’s data and the program. If you want to read a data item in an
object, you call a member function in the object. It will read the item and return the
value to you. You can not access the data directly. Data and its functions are said to be
encapsulated into a single entity. This insulation of data from direct access by the
program is called data hiding.
Inheritance
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification. For
example, the bird robin is a part of the class flying bird, which is again a part of the
class bird. (Refer Figure 8.3). Similarly, manager is a part of class employee. Here
class manager acquires the characteristics of class employee. Hence, manager is the
derived class which has the characteristics of employee which is the base class. The
principle behind this sort of division is that each derived class shares the common
147
characteristics with the class from which it is derived (base class). In OOP, the
concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have combined features
of both the classes. Inheritance allows the programmer to reuse a class, which is not
exactly what he wants, he can tailor the class in such a way that it does not introduce
any side effects into the rest of the classes. Each sub-class defines only those features
that are unique to it. Without the use of classification, each class would have to
explicitly include all of its features.
Inheritance has two complementary roles. It allows a class to be extended so that its
existing functionality can be built on for new applications. It also allows similar
objects to share their common properties and behaviors.
Bird
Attiributes:
Feat hers
Lay eggs
Polymorphism
This is another important OOP concept. The word ‘polymorphism’ is derived from a
Greek word (‘polumorphos’) with two roots
Polus(many) + morphe( shape/form) = Polumorphos
It therefore, means ‘many-shaped’ or ‘having may forms’. In object-oriented
paradigm, it means different forms of data being handled by the same type of process.
Polymorphism means the ability to take more than one form. A operation may exhibit
different behavior in different instances and this behavior depends upon the types of
data used in the operation. For example, consider the addition operation. For two
numbers, the addition operation will generate a sum. If the operands were strings, then
the addition operation would produce a third string by concatenation. Figure 8.4 that a
single function name can be used to handle different number and different types of
arguments.
148
Shape
Draw ()
Dynamic Binding
Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run-time. It is associated with polymorphism and
inheritance. A function call associated with a polymorphic reference depends on the
dynamic type of that reference. By inheritance, every object will have this procedure.
Its algorithm is, however, unique to each object and so the draw procedure will be
redefined in each class that defines the object.
Message Communication
An object-oriented program consists of a set of objects that communicate with each
other. The process of programming in an object-oriented language therefore involves
the following basic steps:
z Creating classes that define objects and their behavior.
z Creating objects from class definitions.
z Establishing communication among objects.
Objects communicate with one another by sending and receiving information much
the same way as people pass messages to one another. A message for an object is a
request for execution of a procedure, and therefore will invoke a function in the
receiving object that generates the desired result. Message passing involves specifying
the name of the object, the name of the function and the information to be sent.
Benefits of OOP
By now, you must be clear about the limitations of procedural approach & how the
object-oriented approach has tried to overcome these limitations. Summarizing the
above concepts, we can list a few advantages of object-oriented approach:
z This method restricts the access to crucial data. Hence, the chances of corrupting
the data accidentally are reduced. Thus it guarantees more reliability.
z Object Oriented Programming makes the task of modifying easy, as you know
which function interact with the given data, thus ensuring better maintainability.
z As data and function are clubbed together into single units, different programmers
in their programs can use these classes. This avoids repetition and provides
reusability. 149
z It simplifies the tasks of writing and debugging. Also since the object contains the
description of data as well as functions, this style provides better readability.
z Through this technique, it’s easier to visualize real-world objects, hence it
becomes easier to design a system.
Student Activity
1. Define classes.
2. What is inheritance?
Summary
In procedural programming, the program is viewed as a sequence of instructions.
The emphasis remains on action where the data is completely ignored throughout the
program. However, no matter how well this process is implemented the larger
programs always become complicated and difficult to maintain.
The increasing complexity of the software gave rise to the concept of object oriented
programming where the emphasis is on data rather than the operation or functions.
Objects are the basic run-time entities in a system. A class binds the data and the
associated methods (called function) together in a single user-defined data-type.
Object-oriented programming is a two-stage process, first identifying and creating
classes, and secondly creating objects of these classes and defining the messages that
pass between them.
In major elements of the object-approach are - abstraction, encapsulation, inheritance,
and polymorphism. The wrapping up of data and functions into a single unit called
class is known as encapsulation.
Inheritance provides the idea of reusability. Additional features can be added to the
existing class without modifying it. Polymorphism is extensively used in
implementing inheritance.
Complex system can be viewed either by focusing upon things or processes; there are
compelling reasons for applying object-oriented decomposition, in which we view the
world as a meaningful collection of objects that collaborate to achieve some higher
level behavior.
Object oriented analysis and design is the method that leads us to an object oriented
decomposition. Object-oriented design defines a notation and process for constructing
complex software systems, and offers a rich set of logical and physical models.
Keywords
Polymorphism: It is derived from a Greek word, which means ‘many-shaped’ or
‘having many forms’.
Dynamic Binding: Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run-time.
150
Review Questions
1. What is the difference between structured programming and object-oriented
programming?
2. When a language has capability to produce new data types, it is said to be :
(a) encapsulated
(b) reprehensible
(c) extensible
3. What is the major issue facing the software industry today?
Further Readings
David N. Smith, Concepts of Object-Oriented Programming, International Books.
Rajesh A, Object Oriented Programming Concepts and Implementation, Laxmi Publications
(P) Ltd.
151
Unit 9 Object-oriented
C Programming Language
Programming
Languages
Unit Structure
• Introduction
• Object-oriented Methods for Design and Development
• Need for New Design Methods
• Classical Business Application and Modern Application
• Modern View of a Business Application
• Different Categories of Analysis and Design Methods
• Applications of Object Technology
• Overview of C++
• Overview of Java
• Summary
• Keywords
• Review Questions
• Further Readings
Learning Objectives
At the conclusion of this unit, you should be able to:
• Describe the need for object-oriented programming languages
• Differentiate between procedural programming languages and object-oriented
programming languages
• Explain various object-oriented concepts
• Discuss the features of C++ programming languages
• Describe the features of Java programming languages
Introduction
As you must have gathered by now that the term Object-oriented does not pertain to
any specific language but is a concept whose cornerstone is object. Today many
languages extensively use this concept. Depending on the features which they support,
these languages can be classified into two categories:
z Object-based programming languages
z Object-oriented programming languages
Object-based programming languages support the following features:
z Data Encapsulation
z Data Hiding
z Automatic Initialization of objects
z Operator Overloading
152
Ada is a typical Object-based programming language. Object-oriented
Programming Languages
Object-oriented programming incorporates all the features of Object-based
programming languages along with two additional features inheritance and dynamic
binding. Examples of these are Simula, C++, Smalltalk ,and Object Pascal. Simula is
about 30 years old & Smalltalk is eighteen years old. Commercially C++ is about
fifteen years old; but looking at the popularity and its wide arena, we’ll be referring to
mainly C++ in further discussions.
Get Formatted
Output
Figure 9.1
Earlier the scope of business application was quiet limited. It was mainly to process
the transaction systematically.
Figure 9.2
In later stages, the scope of business applications has widely increased. They now
involve text as well as graphics. They require elaborate processing such as use of
spreadsheets for business controls, decision making tools, multimedia applications for
better representation etc. As discussed earlier, a billing system these days will not
have only invoices but also the promotional material to be sent to the customer, it
might interact with the customer database. It will also have whatever letters need to
accompany the invoice etc. Similarly stock-management applications these days make
use of multimedia resources to hold and manage technical documentation.
154
Figure 9.3
155
Figure 9.4
The advantages of object-oriented decomposition over the algorithmic decomposition
are as follows:
z Object-oriented decomposition yields smaller systems through the re-use of
common mechanisms, thus providing an important economy of expression.
z Object-orient systems are more resilient to change and thus better able to evolve
over time, because this design is based upon stable intermediate form.
z It greatly reduces the risk of building complex software systems because they are
designed to evolve from smaller system.
z It greatly promotes abstraction, i.e. hiding the inessential details of a complex
object, thus giving an idealized and generalized model.
158
Figure 9.5 the Cartesian, Symentic and Object Approach, respectively.
Information System
Structure Behaviour
Subsystem 1 Subsystem 1
Overview of C++
C++ (pronounced as "C Plus Plus") is a general-purpose programming language. It is
regarded as a middle-level language, as it comprises a combination of both high-level
and low-level language features.
It is a statically typed, free-form, multi-paradigm, compiled language where
compilation creates machine code for a target machine hardware, supports procedural
programming, data abstraction, object-oriented programming, and generic
programming.
The language was developed by Bjarne Stroustrup in 1979 at Bell Labs as an
enhancement to the C programming language and originally named "C with Classes".
It was renamed to C++ in 1983. Enhancements started with the addition of classes,
followed by, among other features, virtual functions, operator overloading, multiple
inheritance, templates, and exception handling.
The C++ programming language standard was ratified in 1998 as ISO/IEC
14882:1998, the current version of which is the 2003 version, ISO/IEC 14882:2003. A
new version of the standard (known informally as C++0x) is being developed.
C++ enjoys wide use in the software industry. Some of its application domains include
systems software, device drivers, embedded software, high-performance server and
client applications, and entertainment software such as video games. Several groups
provide both free and commercial C++ compiler software, including the GNU Project,
Microsoft, Intel, Borland and others.
History
Stroustrup began work on C with Classes in 1979. The idea of creating a new
language originated from Stroustrup's experience in programming for his Ph.D. thesis.
Stroustrup found that Simula had features that were very helpful for large software
development, but the language was too slow for practical use, while BCPL was fast
but too low-level to be suitable for large software development. When Stroustrup
started working in AT&T Bell Labs, he had the problem of analyzing the UNIX kernel
with respect to distributed computing. Remembering his Ph.D. experience, Stroustrup
160 set out to enhance the C language with Simula-like features. C was chosen because it
was general-purpose, fast, portable and widely used. Besides C and Simula, some
other languages that inspired him were ALGOL 68, Ada, CLU and ML. At first, the
class, derived class, strong type checking, inlining, and default argument features were
added to C via Cfront. The first commercial release occurred in October 1985. In
1983, the name of the language was changed from C with Classes to C++ (++ being
the increment operator in C and C++). New features were added including virtual
functions, function name and operator overloading, references, constants, user-
controlled free-store memory control, improved type checking, and BCPL style
single-line comments with two forward slashes (//). In 1985, the first edition of te C++
Programming Language was released, providing an important reference to the
language, since there was not yet an official standard. In 1989, Release 2.0 of C++
was released. New features included multiple inheritance, abstract classes, static
member functions, const member functions, and protected members.
In 1990, the Annotated C++ Reference Manual was published. This work became the
basis for the future standard. Late addition of features included templates, exceptions,
namespaces, new casts, and a Boolean type. As the C++ language evolved, a standard
library also evolved with it.
The first addition to the C++ standard library was the stream I/O library which
provided facilities to replace the traditional C functions such as printf and scanf. Later,
among the most significant additions to the standard library, was the Standard
Template Library.
Language Standard
After years of work, a joint ANSI-ISO committee standardized C++ in 1998. For
some years after the official release of the standard, the committee processed defect
reports, and published a corrected version of the C++ standard in 2003. In 2005, a
technical report, called the "Library Technical Report 1" (often known as TR1 for
short) was released. While not an official part of the standard, it gives a number of
extensions to the standard library, which are expected to be included in the next
version of C++. Support for TR1 is growing in almost all currently maintained C++
compilers. While the C++ language is royalty-free, the standard document itself is not
freely available.
C++ Philosophy
In the Design and Evolution of C++ (1994), Bjarne Stroustrup describes some rules
that he uses for the design of C++:
z C++ is designed to be a statically typed, general-purpose language that is as
efficient and portable as C
z C++ is designed to directly and comprehensively support multiple programming
styles (procedural programming, data abstraction, object-oriented programming,
and generic programming)
z C++ is designed to give the programmer choice, even if this makes it possible for
the programmer to choose incorrectly
z C++ is designed to be as compatible with C as possible, therefore providing a
smooth transition from C
z C++ avoids features that are platform specific or not general purpose
z C++ does not incur overhead for features that are not used (the "zero-overhead
principle")
z C++ is designed to function without a sophisticated programming environment. 161
Standard Library
The 1998 ANSI/ISO C++ standard consists of two parts: the core language and the
C++ standard library; the latter includes most of the Standard Template Library (STL)
and a slightly modified version of the C standard library. Many C++ libraries exist
which are not part of the standard, and, using linkage specification, libraries can even
be written in languages such as C, Fortran, Pascal, or BASIC. Which of these are
supported is compiler dependent.
The C++ standard library incorporates the C standard library with some small
modifications to make it work better with the C++ language. Another large part of
the C++ library is based on the STL. This provides such useful tools as containers
(for example vectors and lists), iterators to provide these containers with array-like
access and algorithms to perform operations such as searching and sorting.
Furthermore (multi)maps (associative arrays) and (multi)sets are provided, all of
which export compatible interfaces. Therefore it is possible, using templates, to write
generic algorithms that work with any container or on any sequence defined by
iterators. As in C, the features of the library are accessed by using the #include
directive to include a standard header. C++ provides 69 standard headers, of which 19
are deprecated.
The STL was originally a third-party library from HP and later SGI, before its
incorporation into the C++ standard. The standard does not refer to it as "STL", as it is
merely a part of the standard library, but many people still use that term to distinguish
it from the rest of the library (input/output streams, internationalization, diagnostics,
the C library subset, etc.).
Most C++ compilers provide an implementation of the C++ standard library, including
the STL. Compiler-independent implementations of the STL, such as STLPort, also
exist. Other projects also produce various custom implementations of the C++
standard library and the STL with various design goals.
Language Features
C++ inherits most of C's syntax and the C preprocessor.
The following is a Hello world program which uses the C++ standard library stream
facility to write a message to standard output:
#include <iostream> // provides std::cout
int main()
{
std::cout << "Hello, world!\n";
return 0;
}
Templates
C++ templates enable generic programming. C++ supports both function and class
templates. Templates may be parameterized by types, compile-time constants, and
other templates. C++ templates are implemented by instantiation at compile-time. To
instantiate a template, compilers substitute specific arguments for a template's
parameters to generate a concrete function or class instance. Templates are a powerful
tool that can be used for generic programming, template meta-programming, and code
optimization, but this power implies a cost. Template use may increase code size,
since each template instantiation produces a copy of the template code: one for each
set of template arguments. This is in contrast to run-time generics seen in other
languages (e.g. Java) where at compile-time the type is erased and a single template
body is preserved.
Templates are different from macros: while both of these compile-time language
features enable conditional compilation, templates are not restricted to lexical
substitution. Templates are aware of the semantics and type system of their companion
language, as well as all compile-time type definitions, and can perform high-level
operations including programmatic flow control based on evaluation of strictly type-
checked parameters. Macros are capable of conditional control over compilation based
on predetermined criteria, but cannot instantiate new types, recurse, or perform type
evaluation and in effect are limited to pre-compilation text-substitution and text-
inclusion/exclusion. In other words, macros can control compilation flow based on
pre-defined symbols but cannot, unlike templates, independently instantiate new
symbols. Templates are a tool for static polymorphism (see below) and generic
programming.
In addition, templates are a compile time mechanism in C++ which is Turing-
complete, meaning that any computation expressible by a computer program can be
computed, in some form, by a template meta-program prior to runtime.
In summary, a template is a compile-time parameterized function or class written
without knowledge of the specific arguments used to instantiate it. After instantiation
the resulting code is equivalent to code written specifically for the passed arguments.
In this manner, templates provide a way to decouple generic, broadly-applicable
aspects of functions and classes (encoded in templates) from specific aspects (encoded
in template parameters) without sacrificing performance due to abstraction.
Objects
C++ introduces object-oriented (OO) features to C. It offers classes, which provide the
four features commonly present in OO (and some non-OO) languages: abstraction,
encapsulation, inheritance, and polymorphism. Objects are instances of classes created
at runtime. The class can be thought of as a template from which many different
individual objects may be generated as a program runs.
Encapsulation
Encapsulation is the hiding of information. C++ implements encapsulation by
allowing all members of a class to be declared as either public, private, or protected. A
public member of the class is accessible to any function. A private member is
accessible only to functions that are members of that class and to functions and classes
explicitly granted access permission by the class ("friends"). A protected member is
accessible to members of classes that inherit from the class in addition to the class 163
itself and any friends.
The OO principle is that all of the functions (and only the functions) that access the
internal representation of a type should be encapsulated within the type definition.
C++ supports this (via member functions and friend functions), but does not enforce
it: the programmer can declare parts or all of the representation of a type to be public,
and is allowed to make public entities that are not part of the representation of the
type.
Because of this, C++ supports not just OO programming, but other weaker
decomposition paradigms, like modular programming. It is generally considered good
practice to make all data private or protected, and to make public only those functions
that are part of a minimal interface for users of the class. This hides all the details of
data implementation, allowing the designer to later fundamentally change the
implementation without changing the interface in any way.
Inheritance
Inheritance allows one data type to acquire properties of other data types. Inheritance
from a base class may be declared as public, protected, or private. This access
specifier determines whether unrelated and derived classes can access the inherited
public and protected members of the base class. Only public inheritance corresponds
to what is usually meant by "inheritance". The other two forms are much less
frequently used. If the access specifier is omitted, a "class" inherits privately, while a
"struct" inherits publicly. Base classes may be declared as virtual; this is called virtual
inheritance. Virtual inheritance ensures that only one instance of a base class exists in
the inheritance graph, avoiding some of the ambiguity problems of multiple
inheritance.
Multiple inheritance is a C++ feature sometimes considered controversial. Multiple
inheritance allows a class to be derived from more than one base class; this can result
in a complicated graph of inheritance relationships. For example, a "Flying Cat" class
can inherit from both "Cat" and "Flying Mammal". Some other languages, such as
Java or C#, accomplish something similar (although more limited) by allowing
inheritance of multiple interfaces while restricting the number of base classes to one
(interfaces, unlike classes, provide only declarations of member functions, no
implementation or member data).
Polymorphism
Polymorphism enables one common interface for many implementations, and for
objects to act differently under different circumstances. C++ supports several kinds of
static (compile-time) and dynamic (run-time) polymorphisms. Compile-time
polymorphism does not allow for certain run-time decisions, while run-time
polymorphism typically incurs a performance penalty.
Static Polymorphism
Function overloading allows programs to declare multiple functions having the same
name (but with different arguments). The functions are distinguished by the number
and/or types of their formal parameters. Thus, the same function name can refer to
different functions depending on the context in which it is used. The type returned by
the function is not used to distinguish overloaded functions.
When declaring a function, a programmer can specify default arguments for one or
more parameters. Doing so allows the parameters with defaults to optionally be
omitted when the function is called, in which case the default arguments will be used.
When a function is called with fewer arguments than there are declared parameters,
explicit arguments are matched to parameters in left-to-right order, with any
164
unmatched parameters at the end of the parameter list being assigned their default
arguments. In many cases, specifying default arguments in a single function
declaration is preferable to providing overloaded function definitions with different
numbers of parameters.
Templates in C++ provide a sophisticated mechanism for writing generic,
polymorphic code. In particular, through the Curiously Recurring Template Pattern it's
possible to implement a form of static polymorphism that closely mimics the syntax
for overriding virtual functions. Since C++ templates are type-aware and Turing-
complete they can also be used to let the compiler resolve recursive conditionals and
generate substantial programs through template metaprogramming.
Dynamic Polymorphism
Inheritance
Variable pointers (and references) to a base class type in C++ can refer to objects of
any derived classes of that type in addition to objects exactly matching the variable
type. This allows arrays and other kinds of containers to hold pointers to objects of
differing types. Because assignment of values to variables usually occurs at run-time,
this is necessarily a run-time phenomenon.
C++ also provides a dynamic_cast operator, which allows the program to safely
attempt conversion of an object into an object of a more specific object type (as
opposed to conversion to a more general type, which is always allowed). This feature
relies on run-time type information (RTTI). Objects known to be of a certain specific
type can also be cast to that type with static_cast, a purely compile-time construct
which is faster and does not require RTTI.
Overview of Java
A high-level programming language developed by Sun Microsystems. Java was
originally called OAK, and was designed for handheld devices and set-top boxes. Oak
was unsuccessful so in 1995 Sun changed the name to Java and modified the language
to take advantage of the burgeoning World Wide Web. The language derives much of
its syntax from C and C++ but has a simpler object model and fewer low-level
facilities. Java applications are typically compiled to bytecode that can run on any
Java Virtual Machine (JVM) regardless of computer architecture.
Java is an object-oriented language similar to C++, but simplified to eliminate
language features that cause common programming errors. Java source code files
(files with a .java extension) are compiled into a format called bytecode (files with a
.class extension), which can then be executed by a Java interpreter. Compiled Java
code can run on most computers because Java interpreters and runtime environments,
known as Java Virtual Machines (JVMs), exist for most operating systems, including
UNIX, the Macintosh OS, and Windows. Bytecode can also be converted directly into
machine language instructions by a Just-in-Time compiler (JIT).
Java is a general purpose programming language with a number of features that make
the language well suited for use on the World Wide Web. Small Java applications are
called Java applets and can be downloaded from a Web server and run on your
computer by a Java-compatible Web browser, such as Netscape Navigator or
Microsoft Internet Explorer.
The original and reference implementation Java compilers, virtual machines, and class
libraries were developed by Sun from 1995. As of May 2007, in compliance with the
specifications of the Java Community Process, Sun made available most of their Java
technologies as free software under the GNU General Public License. Others have
166
also developed alternative implementations of these Sun technologies, such as the
GNU Compiler for Java and GNU Classpath.
James Gosling initiated the Java language project in June 1991 for use in one of his
many set-top box projects. The language, initially called Oak after an oak tree that
stood outside Gosling's office, also went by the name Green and ended up later
renamed as Java, from a list of random words. Gosling aimed to implement a virtual
machine and a language that had a familiar C/C++ style of notation.
Sun released the first public implementation as Java 1.0 in 1996. It promised "Write
Once, Run Anywhere" (WORA), providing no-cost run-times on popular platforms.
Fairly secure and featuring configurable security, it allowed network- and file-access
restrictions. Major web browsers soon incorporated the ability to run secure Java
applets within web pages, and Java quickly became popular. With the advent of Java 2
(released initially as J2SE 1.2 in December 1998), new versions had multiple
configurations built for different types of platforms. For example, J2EE targeted
enterprise applications and the greatly stripped-down version J2ME for mobile
applications. J2SE designated the Standard Edition. In 2006, for marketing purposes,
Sun renamed new J2 versions as Java EE, Java ME, and Java SE, respectively.
At one time, Sun made most of its Java implementations available without charge,
despite their proprietary software status. Sun generated revenue from Java through the
selling of licenses for specialized products such as the Java Enterprise System. Sun
distinguishes between its Software Development Kit (SDK) and Runtime
Environment (JRE) (a subset of the SDK); the primary distinction involves the JRE's
lack of the compiler, utility programs, and many necessary header files.
On 13th November 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL). On 8th May 2007 Sun
finished the process, making all of Java's core code free and open-source, aside from a
small portion of code to which Sun did not hold the copyright.
Java Philosophy
There were five main goals in the development of the Java language:
1. It should be "simple, object-oriented, and familiar".
2. It should be "robust and secure".
3. It should be "architecture neutral and portable".
4. It should execute with "high performance".
5. It should be "interpreted, threaded, and dynamic".
Java Platform
One characteristic of Java is portability, which means that computer programs written
in the Java language must run similarly on any supported hardware/operating-system
platform. One should be able to write a program once, compile it once, and run it
anywhere.
This is achieved by compiling the Java language code, not to machine code but to Java
bytecode – instructions analogous to machine code but intended to be interpreted by a
Virtual Machine (VM) written specifically for the host hardware. End-users
commonly use a JRE installed on their own machine, or in a Web browser.
Standardized libraries provide a generic way to access host specific features such as
graphics, threading and networking. In some JVM versions, bytecode can be compiled
167
to native code, either before or during program execution, resulting in faster
execution.
A major benefit of using bytecode is Porting. However, the overhead of interpretation
means that interpreted programs almost always run more slowly than programs
compiled to native executables would, and Java suffered a reputation for poor
performance. This gap has been narrowed by a number of optimisation techniques
introduced in the more recent JVM implementations.
One such technique, known as (just-in-time compilation) JIT, translates Java bytecode
into native code the first time that code is executed, then caches it. This results in a
program that starts and executes faster than pure interpreted code can, at the cost of
introducing occasional compilation overhead during execution. More sophisticated
VMs also use dynamic recompilation, in which the VM analyzes the behavior of the
running program and selectively recompiles and optimizes parts of the program.
Dynamic recompilation can achieve optimizations superior to static compilation
because the dynamic compiler can base optimizations on knowledge about the runtime
environment and the set of loaded classes, and can identify hot spots - parts of the
program, often inner loops, that take up the most execution time. JIT compilation and
dynamic recompilation allow Java programs to approach the speed of native code
without losing portability.
Another technique, commonly known as static compilation, or Ahead-of-Time (AOT)
compilation, is to compile directly into native code like a more traditional compiler.
Static Java compilers translate the Java source or bytecode to native object code. This
achieves good performance compared to interpretation, at the expense of portability;
the output of these compilers can only be run on a single architecture. AOT could give
Java something like performance, yet it is still not portable since there are no compiler
directives, and all the pointers are indirect with no way to micro manage garbage
collection.
Java's performance has improved substantially since the early versions, and
performance of JIT compilers relative to native compilers has in some tests been
shown to be quite similar. The performance of the compilers does not necessarily
indicate the performance of the compiled code; only careful testing can reveal the true
performance issues in any system.
One of the unique advantages of the concept of a runtime engine is that errors
(exceptions) should not 'crash' the system. Moreover, in runtime engine environments
such as Java there exist tools that attach to the runtime engine and every time that an
exception of interest occurs they record debugging information that existed in memory
at the time the exception was thrown (stack and heap values). These Automated
Exception Handling tools provide 'root-cause' information for exceptions in Java
programs that run in production, testing or development environments.
Implementations
Sun Microsystems officially licenses the Java Standard Edition platform for Microsoft
Windows, Linux, and Solaris. Through a network of third-party vendors and licensees,
alternative Java environments are available for these and other platforms.
Sun's trademark license for usage of the Java brand insists that all implementations be
"compatible". This resulted from a legal dispute with Microsoft after Sun claimed that
the Microsoft implementation did not support RMI or JNI and had added platform-
specific features of their own. Sun sued in 1997, and in 2001 won a settlement of $20
million as well as a court order enforcing the terms of the license from Sun. As a
result, Microsoft no longer ships Java with Windows, and in recent versions of
168 Windows, Internet Explorer cannot support Java applets without a third-party plugin.
Sun, and others, has made available free Java run-time systems for those and other
versions of Windows.
Platform-independent Java is essential to the Java Enterprise Edition strategy, and an
even more rigorous validation is required to certify an implementation. This
environment enables portable server-side applications, such as Web services, servlets,
and Enterprise JavaBeans, as well as with embedded systems based on OSGi, using
Embedded Java environments. Through the new GlassFish project, Sun is working to
create a fully functional, unified open-source implementation of the Java EE
technologies.
Sun also distributes a superset of the JRE called the Java 2 SDK (more commonly
known as the JDK), which includes development tools such as the Java compiler,
Javadoc, Jar and debugger.
169
Java Programming Style
The syntax of Java is largely derived from C++. Unlike C++, which combines the
syntax for structured, generic, and object-oriented programming, Java was built almost
exclusively as an object-oriented language. All code is written inside a class and
everything is an object, with the exception of the intrinsic data types (ordinal and real
numbers, boolean values, and characters), which are not classes for performance
reasons.
Java suppresses several features (such as operator overloading and multiple
inheritance) for classes in order to simplify the language and to prevent possible errors
and anti-pattern design.
Example
Welcome to India
The canonical Hello world program can be written in Java as:
// HelloWorld.java
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to India!");
}
}
By convention, source files are named after the public class they contain, appending
the suffix .java, for example, Welcome.java. It must first be compiled into bytecode,
using a Java compiler, producing a file named Welcome.class. Only then can it be
executed, or 'launched'. The java source file may only contain one public class but can
contain multiple classes with less than public access, which can only be accessed from
other classes within the file.
A class that is declared private may be stored in any .java file. The compiler will
generate a class file for each class defined in the source file. The name of the class file
is the name of the class, with .class appended. For class file generation, anonymous
classes are treated as if their name was the concatenation of the name of their
enclosing class, a $, and an integer.
The keyword public denotes that a method can be called from code in other classes, or
that a class may be used by classes outside the class hierarchy. The class hierarchy is
related to the name of the directory in which the .java file is.
The keyword static in front of a method indicates a static method, which is associated
only with the class and not with any specific instance of that class. Only static
methods can be invoked without a reference to an object. Static methods cannot access
any method variables that are not static.
The keyword void indicates that the main method does not return any value to the
caller. If a Java program is to exit with an error code, it must call System.exit()
The method name "main" is not a keyword in the Java language. It is simply the name
of the method the Java launcher calls to pass control to the program. Java classes that
run in managed environments such as applets and Enterprise Java Beans do not use or
need a main() method. A java program may contain multiple classes that have main
methods, which means that the VM needs to be explicitly told which class to launch
from.
170
The main method must accept an array of String objects. By convention, it is
referenced as args although any other legal identifier name can be used. Since Java 5,
the main method can also use variable arguments, in the form of public static void
main(String... args), allowing the main method to be invoked with an arbitrary number
of String arguments. The effect of this alternate declaration is semantically identical
(the args parameter is still an array of String objects), but allows an alternate syntax
for creating and passing the array.
The Java launcher launches Java by loading a given class (specified on the command
line or as a attribute in a JAR) and starting its public static void main(String[])
method. Stand-alone programs must declare this method explicitly. The String[] args
parameter is an array of String objects containing any arguments passed to the class.
The parameters to main are often passed by means of a command line.
Printing is part of a Java standard library: The System class defines a public static
field called out. The out object is an instance of the PrintStream class and provides
many methods for printing data to standard out, including println(String) which also
appends a new line to the passed string.
The string "Welcome to India!" is automagically converted to a String object by the
compiler.
Example
// OddEven.java
import javax.swing.JOptionPane;
public class OddEven {
// "input" is the number that the user gives to the computer
private int input; // a whole number("int" means integer)
/*
* This is the constructor method. It gets called when an object of the OddEven type
* is being created.
*/
public OddEven() {}
// This is the main method. It gets called when this class is run through a Java
interpreter.
public static void main(String[] args) {
/*
* This line of code creates a new instance of this class called "number" and
* initializes it, and the next line of code calls the "showDialog()" method,
* which brings up a prompt to ask you for a number
*/
OddEven number = new OddEven();
number.showDialog();
}
public void showDialog() {
171
/*
* "try" makes sure nothing goes wrong. If something does,
* the interpreter skips to "catch" to see what it should do.
*/
try {
/*
* The code below brings up a JOptionPane, which is a dialog box
* The String returned by the "showInputDialog()" method is converted into
* an integer, making the program treat it as a number instead of a word.
* After that, this method calls a second method, calculate() that will
* display either "Even" or "Odd."
*/
input = Integer.parseInt(JOptionPane.showInputDialog ("Please Enter A
Number"));
calculate();
} catch (NumberFormatException e) {
/*
* Getting in the catch block means that there was a problem with the format of
* the number. Probably some letters were typed in instead of a number.
*/
System.err.println("ERROR: Invalid input. Please type in a numerical value.");
}
}
/*
* When this gets called, it sends a message to the interpreter.
*/
private void calculate() {
if (input % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
}
z The import statement imports the JOptionPane class from the javax.swing
package.
z The OddEven class declares a single private field of type int named input. Every
instance of the OddEven class has its own copy of the input field. The private
declaration means that no other class can access (read or write) the input field.
172
z OddEven() is a public constructor. Constructors have the same name as the
enclosing class they are declared in, and unlike a method, have no return type. A
constructor is used to initialize an object that is a newly created instance of the
class. The dialog returns a String that is converted to an int by the
Integer.parseInt(String) method.
z The calculate() method is declared without the static keyword. This means that the
method is invoked using a specific instance of the OddEven class. (The reference
used to invoke the method is passed as an undeclared parameter of type OddEven
named this.) The method tests the expression input % 2 == 0 using the if keyword
to see if the remainder of dividing the input field belonging to the instance of the
class by two is zero. If this expression is true, then it prints Even; if this
expression is false it prints Odd. (The input field can be equivalently accessed as
this.input, which explicitly uses the undeclared this parameter.)
z OddEven number = new OddEven(); declares a local object reference variable in
the main method named number. This variable can hold a reference to an object of
type OddEven. The declaration initializes number by first creating an instance of
the OddEven class, using the new keyword and the OddEven() constructor, and
then assigning this instance to the variable.
z The statement number.showDialog(); calls the calculate method. The instance of
OddEven object referenced by the number local variable is used to invoke the
method and passed as the undeclared this parameter to the calculate method.
Special Classes
Applet
Java applets are programs that are embedded in other applications, typically in a Web
page displayed in a Web browser.
// Hello.java
import java.applet.Applet;
import java.awt.Graphics;
public class Hello extends Applet {
public void paint(Graphics gc) {
gc.drawString("Hello, world!", 65, 95);
}
}
The import statements direct the Java compiler to include the java.applet.Applet and
java.awt. Graphics classes in the compilation. The import statement allows these
classes to be referenced in the source code using the simple class name (i.e. Applet)
instead of the fully qualified class name (i.e. java.applet.Applet).
The Hello class extends (subclasses) the Applet class; the Applet class provides the
framework for the host application to display and control the lifecycle of the applet.
The Applet class is an Abstract Windowing Toolkit (AWT) Component, which
provides the applet with the capability to display a graphical user interface (GUI) and
respond to user events.
The Hello class overrides the paint(Graphics) method inherited from the Container
superclass to provide the code to display the applet. The paint() method is passed a
Graphics object that contains the graphic context used to display the applet. The
paint() method calls the graphic context drawString(String, int, int) method to display 173
the "Hello, world!" string at a pixel offset of (65, 95) from the upper-left corner in the
applet's display.
<!-- Hello.html -->
<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code="Hello" width="200" height="200">
</applet>
</body>
</html>
An applet is placed in an HTML document using the <applet> HTML element. The
applet tag has three attributes set: code="Hello" specifies the name of the Applet class
and width="200" height="200" sets the pixel width and height of the applet. Applets
may also be embedded in HTML using either the object or embed element[15],
although support for these elements by Web browsers is inconsistent.[16] However,
the applet tag is deprecated, so the object tag is preferred where supported.
The host application, typically a Web browser, instantiates the Hello applet and
creates an Applet Context for the applet. Once the applet has initialized itself, it is
added to the AWT display hierarchy. The paint method is called by the AWT event
dispatching thread whenever the display needs the applet to draw itself.
Servlet
Java Servlet technology provides Web developers with a simple, consistent
mechanism for extending the functionality of a Web server and for accessing existing
business systems. Servlets are server-side Java EE components that generate responses
(typically HTML pages) to requests (typically HTTP requests) from clients. A servlet
can almost be thought of as an applet that runs on the server side—without a face.
// Hello.java
import java.io.*;
import javax.servlet.*;
public class Hello extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
final PrintWriter pw = response.getWriter();
pw.println("Hello, world!");
pw.close();
}
}
The import statements direct the Java compiler to include all of the public classes and
174
interfaces from the java.io and javax.servlet packages in the compilation.
The Hello class extends the GenericServlet class; the GenericServlet class provides
the interface for the server to forward requests to the servlet and control the servlet's
lifecycle.
The Hello class overrides the service(ServletRequest, ServletResponse) method
defined by the Servlet interface to provide the code for the service request handler.
The service() method is passed a ServletRequest object that contains the request from
the client and a ServletResponse object used to create the response returned to the
client. The service() method declares that it throws the exceptions ServletException
and IOException if a problem prevents it from responding to the request.
The setContentType(String) method in the response object is called to set the MIME
content type of the returned data to "text/html". The getWriter() method in the
response returns a PrintWriter object that is used to write the data that is sent to the
client. The println(String) method is called to write the "Hello, world!" string to the
response and then the close() method is called to close the print writer, which causes
the data that has been written to the stream to be returned to the client.
JavaServer Page
JavaServer Pages (JSPs) are server-side Java EE components that generate responses,
typically HTML pages, to HTTP requests from clients. JSPs embed Java code in an
HTML page by using the special delimiters <% and %>. A JSP is compiled to a Java
servlet, a Java application in its own right, the first time it is accessed. After that, the
generated servlet creates the response.
Swing Application
Swing is a graphical user interface library for the Java SE platform. It is possible to
specify a different look and feel through the pluggable look and feel system of Swing.
Clones of Windows, GTK and Motif are supplied by Sun. Apple also provides an
Aqua look and feel for Mac OS X. Though prior implementations of these looks and
feels have been considered lacking,[citation needed] Swing in Java SE 6 addresses this
problem by using more native widget drawing routines of the underlying platforms.
This example Swing application creates a single window with "Hello, world!" inside:
// Hello.java (Java SE 5)
import java.awt.BorderLayout;
import javax.swing.*;
public class Hello extends JFrame {
public Hello() {
super("hello");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(new JLabel("Hello, world!"));
pack();
}
public static void main(String[] args) {
new Hello().setVisible(true);
}
}
175
The first import statement directs the Java compiler to include the BorderLayout class
from the java.awt package in the compilation; the second import includes all of the
public classes and interfaces from the javax.swing package.
The Hello class extends the JFrame class; the JFrame class implements a window with
a title bar and a close control.
The Hello() constructor initializes the frame by first calling the superclass constructor,
passing the parameter "hello", which is used as the window's title. It then calls the
setDefaultCloseOperation(int) method inherited from JFrame to set the default
operation when the close control on the title bar is selected to
WindowConstants.EXIT_ON_CLOSE — this causes the JFrame to be disposed of
when the frame is closed (as opposed to merely hidden), which allows the JVM to exit
and the program to terminate. Next, the layout of the frame is set to a BorderLayout;
this tells Swing how to arrange the components that will be added to the frame. A
JLabel is created for the string "Hello, world!" and the add(Component) method
inherited from the Container superclass is called to add the label to the frame. The
pack() method inherited from the Window superclass is called to size the window and
lay out its contents, in the manner indicated by the BorderLayout.
The main() method is called by the JVM when the program starts. It instantiates a new
Hello frame and causes it to be displayed by calling the setVisible(boolean) method
inherited from the Component superclass with the boolean parameter true. Note that
once the frame is displayed, exiting the main method does not cause the program to
terminate because the AWT event dispatching thread remains active until all of the
Swing top-level windows have been disposed.
Java Generics
Prior to generics, each variable declaration had to be of a specific type. For container
classes, for example, this is a problem because there is no easy way to create a
container that accepts only specific types of objects. Either the container operates on
all subtypes of a class or interface, usually Object, or a different container class has to
be created for each contained class. Generics allow compile-time type checking
without having to create a large number of container classes, each containing almost
identical code.
Class Libraries
Java libraries are the compiled byte codes of source code developed by the JRE
implementor to support application development in Java. Examples of these libraries
are:
1. The core libraries, which include:
Collection libraries that implement data structures such as lists, dictionaries,
trees and sets
XML Processing (Parsing, Transforming, Validating) libraries
Security
Internationalization and localization libraries
2. The integration libraries, which allow the application writer to communicate with
external systems. These libraries include:
The Java Database Connectivity (JDBC) API for database access
Java Naming and Directory Interface (JNDI) for lookup and discovery
Java Editions
Java comes in various editions depending on their application areas:
z Java Card
z Micro Edition (ME)
z Standard Edition (SE)
z Enterprise Edition (EE)
z PersonalJava (discontinued)
Sun has defined and supports four editions of Java targeting different application
environments and segmented many of its APIs so that they belong to one of the
platforms. The platforms are:
z Java Card for smartcards
z Java Platform, Micro Edition (Java ME) — targeting environments with limited
resources,
z Java Platform, Standard Edition (Java SE) — targeting workstation environments,
and
z Java Platform, Enterprise Edition (Java EE) — targeting large distributed
enterprise or Internet environments.
The classes in the Java APIs are organized into separate groups called packages. Each
package contains a set of related interfaces, classes and exceptions. Refer to the
separate platforms for a description of the packages available.
The set of APIs is controlled by Sun Microsystems in cooperation with others through
the Java Community Process program. Companies or individuals participating in this
process can influence the design and development of the APIs. This process has been
a subject of controversy.
Sun also provided an edition called PersonalJava that has been superseded by later,
standards-based Java ME configuration-profile pairings.
177
Student Activity
1. Discuss about modern view of business applications.
2. Write a note on first generation approach.
Summary
To achieve the objective of creating a comprehensive and simple model of a system, a
complex system is decomposed into smaller parts, which are further broken down into
simpler parts.
The classical business application consists, on the one hand of storing and retrieving
coded and structured items of information and, on the other of performing symbolic
transformation or arithmetical calculations.
Object-oriented programming has changed the way we build and design software.
Applications of OOP are beginning to gain wide importance; designing GUI
(Graphical User Interface) being the most popular of them.
Java was originally called OAK, and was designed for handheld devices and set-top
boxes.
Keywords
Templates: Templates are a powerful tool that can be used for generic programming,
template meta-programming, and code optimization, but this power implies a cost.
Encapsulation: Encapsulation is the hiding of information. C++ implements
encapsulation by allowing all members of a class to be declared as either public,
private, or protected.
Java: Java is an object-oriented language similar to C++, but simplified to eliminate
language features that cause common programming errors.
Review Questions
1. Discuss the importance of Java in web development.
2. Discuss the application areas of C++ languages.
Further Readings
Kanetkat Yaswant, Let Us C++.
E Balaguruswamy, Programming in C++.
Herbert Schildt, C++ The Complete Reference, Third Edition, Osborne McGraw-Hill.
Stroustrup, Bjarne, The C++ Programming Language, Special Edition, Addison-Wesley.
Lippman, Stanley B.; Josée Lajoie, Barbara E. Moo, C++ Primer, 2005.
E Balaguruswamy, Programming with Java, A Primer, Tata McGraw Hill, India.
Aaron E Walsh, Foundation of Java Programming for the World Wide Web, IDG Books
Worldwide, 1996.
Davis Stephen R, Learn Java Now, Microsoft Press, 1996.
Naughton Patrick, The Java Handbook, Osbrone McGraw Hill, 1996.
Norton Peter and William Stanek, Guide to Java Programming, Sames.net, 1996.
178