0% found this document useful (0 votes)
1 views

Object Oriented Programming Through Java P Radha Krishna instant download

The document is about the book 'Object Oriented Programming Through Java' by P Radha Krishna, which serves as an introduction to Java and object-oriented programming concepts. It covers various topics including Java fundamentals, OOP principles, exception handling, multithreading, and database connectivity. The book is aimed at undergraduate and postgraduate engineering students and includes exercises and questions for practice.

Uploaded by

adasfamazura
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Object Oriented Programming Through Java P Radha Krishna instant download

The document is about the book 'Object Oriented Programming Through Java' by P Radha Krishna, which serves as an introduction to Java and object-oriented programming concepts. It covers various topics including Java fundamentals, OOP principles, exception handling, multithreading, and database connectivity. The book is aimed at undergraduate and postgraduate engineering students and includes exercises and questions for practice.

Uploaded by

adasfamazura
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Object Oriented Programming Through Java P Radha

Krishna download

https://ebookbell.com/product/object-oriented-programming-
through-java-p-radha-krishna-43702704

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Java Programming Fundamentals Problem Solving Through Object Oriented


Analysis And Design 1st Edition Premchand S Nair

https://ebookbell.com/product/java-programming-fundamentals-problem-
solving-through-object-oriented-analysis-and-design-1st-edition-
premchand-s-nair-2406494

Object Oriented Programming Through C As Per The Latest Syllabus Of


Jntu Kakinadaregulation 2014 E Balagurusamy

https://ebookbell.com/product/object-oriented-programming-through-c-
as-per-the-latest-syllabus-of-jntu-
kakinadaregulation-2014-e-balagurusamy-10959564

Objectoriented Programming In C Nicolai M Josuttis

https://ebookbell.com/product/objectoriented-programming-in-c-nicolai-
m-josuttis-46086084

Object Oriented Programming In Vbnet 1st Edition Alistair Mcmonnies

https://ebookbell.com/product/object-oriented-programming-in-
vbnet-1st-edition-alistair-mcmonnies-55132326
Objectoriented Programming In C Sourav Sahay

https://ebookbell.com/product/objectoriented-programming-in-c-sourav-
sahay-55234334

Object Oriented Programminghardmanv1pdf Amany Fawzy Elgamal

https://ebookbell.com/product/object-oriented-programminghardmanv1pdf-
amany-fawzy-elgamal-56094468

Objectoriented Programming With Visual Basicnet Michael Mcmillan

https://ebookbell.com/product/objectoriented-programming-with-visual-
basicnet-michael-mcmillan-2004060

Objectoriented Programming Languages Interpretation Iain D Craig

https://ebookbell.com/product/objectoriented-programming-languages-
interpretation-iain-d-craig-2095070

Objectoriented Programming In C 7th Print With Corrections Lafore

https://ebookbell.com/product/objectoriented-programming-in-c-7th-
print-with-corrections-lafore-21984516
~
§)) Universities Press COMPUTER SCIENCE

Object Oriented Programming through

| P Radha Krishna
Object Oriented Programming through

Java”
Other Related Titles Published by Universities Press

Data Structures, Algorithms, and Applications in JAVA (2nd Edition)


Sartaj Sahni

Data Structures, Algorithms and Applications in C++ (2nd edition)


Sartaj Sahni

The C Programmer’s Companion — ANSI C Library Functions


R. S. Jones

C: An Advanced Introduction: ANSI C Edition


Narain Gehani

Data Mining Techniques


Arun K. Pujari

www.universitiespress.com
Object Oriented Programming through

Java"

P Radha Krishna
Associate Professor,
Institute for Development and Research in Banking
Technology, Hyderabad

D
Universities Press
Universities Press (India) Private Limited

Registered Office
3-5-819 Hyderguda, Hyderabad 500 029 (A.P.), India
e-mail: info@universitiespress.com

Distributed by
Orient Longman Private Limited

Registered Office
3-6-752 Himayatnagar, Hyderabad 500 029 (A.P.), India
email: cogeneral@orientlongman.com

Other Offices
Bangalore / Bhopal / Bhubaneshwar / Chennai
Ernakulam / Guwahati / Hyderabad / Jaipur / Kolkata
Lucknow / Mumbai / New Delhi / Patna

© Universities Press (India) Private Limited 2007


First published 2007

Cover and book design


© Universities Press (India) Private Limited 2006

ISBN 13: 978 - 81 - 7371 - 572 -3


ISBN 10: 81 - 7371 - 572 - 6

Set in Times New Roman 11 points by


Sigma Publishing Services, Chennai 600 033

Printed at
Brijbasi Art Press Ltd
New Delhi - 110 020

Published by
Universities Press (India) Private Limited
3-5-819, Hyderguda, Hyderabad 500 029

All product names mentioned in the book are trademarks or registered trademarks of their respective owners. Where we
were aware of this we have represented the names within the text in initial capitals, all capitals or medial capitals.
To
My parents
(Sri P Rama Murthy and Smt P Kameswari)
>
ruoweamnyAD tn? hen GME maTyW BAZ —
or ae

is

Pies ine
7
oe ee ee ee
_
oo ‘ace iar eis (Fee

7
<a nba iy
seal a
-
©

Sa
—_
™ 7-
Preface

No programming language has ever gathered as many adherents in such a short span as Java. A
product of Sun Microsystems, Java gels well with web browsers and has great features such as
Object Oriented Programming, GUI programming, Database Access and Networking and also has
in-built security.
Java came into the public domain in mid-1995, and since then its popularity has sky-rocketed.
In a mere six months, Java was being used by over one hundred thousand programmers. By 2000,
the number of Java users reached one million, and this number is multiplying by thousands every
year. It is this increasing demand that has resulted in over half a million programmers registering
with the Sun Java Developer Group.
Complex programs are built into simple, smaller constructs called objects by using the
concepts of object oriented programming (OOP). The various characteristics of OOP include
classes, abstraction, inheritance, polymorphism and encapsulation. This book is an introduction to
Java and object oriented programming to readers who are not familiar with the world of Java. This
book, spread over fourteen chapters, is designed for undergraduate and post-graduate engineering
and technology students.
Chapter | covers the basics features of object oriented programming and Chapter 2 presents
a brief introduction to Java along with an overview of arrays, methods and structures in Java. A
summary on Java applications and applets is also provided to familiarize the reader with Java
programming. This chapter is designed to introduce beginners to Java programming concepts,
while experienced programmers would find it helpful in revising their skills.
Chapter 3, divided into two parts, deals with the fundamentals of Java programming language.
While the first part is on various data types in Java, literals, identifiers, operators and the like, the
second part focuses on various control statements and arrays in Java. Chapter 4 deals with various
object oriented programming concepts in the context of Java programming language.
Java offers an exception-handling mechanism which is easy to understand and implement, and
Chapter 5 provides an insight in exception handling. Multithreading is a powerful programming
tool that makes concurrent execution of multiple units of a program happen. A brief overview on
multithreading is provided in Chapter 6.
Chapter 7 covers various input and output streams provided in Java for reading and writing data.
Chapter 8 covers the essentials of applets and their life cycle. Applets are useful for client-side
programming and facilitate graphics. A programming-level interface for communicating with
Vili. Preface

databases using Java programming language is provided by JDBC. Chapter 9 covers Java constructs
useful in handling databases. An overview of Graphical User Interface (GUI) features of Java has
been presented in Chapter 10, and Chapter 11 provides a brief on swings programming.
The servlet is a key component of server-side Java development, and Chapter 12 focuses on
programming servlets. Java supports easy writing of network applications by not considering
much of the implementation details, which are operating system—Specific. Chapter 13 is on Java
support for network programming and remote method invocation. Chapter 14 presents the new
language features of Java 1.5.

_ Acknowledgements
It is a great pleasure for me to acknowledge the assistance and contributions of a large number of
the individuals to this effort. First, I would like to thank the faculty members and staff of IDRBT
who made it easier for me to carry out my work. I would also like to express my sincere gratitude
to Raja Ramesh, V Bharat Kumar, P Seema, P Deepthi and V Sandhya who, with their valuable
suggestions and contribution, helped enhance the quality of this book.
The impetus for the book came from Pradeep Kumar, who has worked closely with me during
the preparation of final manuscript. I would like to record my thanks to the students of M. Tech.
IT (Banking Technology and Information Security), a collaborative programme of the University
of Hyderabad and the Institute for Development and Research on Banking Technology (IDRBT).
This book is a result of quality discussions and deliberations between the students and me. Some
of the updated material from Sun Systems have been referred to while explaining concepts to
students. I would like to acknowledge this.
My sincere thanks also go to Mr Madhu Reddy of Universities Press, ae speeded up the
process and made it possible to publish this book in a very short span of time. My special thanks
are due to Ms Shubashree Desikan, editor at Universities Press, who has helped me present my
thoughts in manner easier to understand. Last but not the least, I would like to thank my family
members, without whose active support and cooperation, this book would not have seen the light
of the day.
P Radha Krishna
Contents

Preface

Chapter 1 Object Oriented Programming

1.1 Introduction to OOP


ig2 Objects and Classes
1.3 Characteristics of OOP
1.3.1 Encapsulation
1.3.2 Inheritance
1.3.3. Polymorphism
1.4 Difference between OOP and Procedure Oriented Programming
1.5 Summary
1.5.1 Benefits of OOP
1.5.2 Drawbacks of OOP
1.5.3 Challenges of OOP
Objective type questions
Exercises
Answers

Chapter 2 Introduction to Java Programming

2A Introduction
2.1.1 Overview of Java technology
2.1.2 Ashort history of the development of Java
2.1.3 Java as anew paradigm in programming
22 Features of Java
23 Comparing Java and Other Languages
2.4 Applications and Applets
2.4.1 Simple applications using Java
2.4.2 Other applications and applets
2.5 Java Development Kit
2.6 More Complex Programs
Contents

Ze} Java Source File Structure 30


MS Prerequisites for Compiling and Running Java Programs 3
Objective type questions a2,
Exercises 32
Answers a2

Chapter 3 Java Language Fundamentals 33

ate The Building Blocks of Java 33


3.1.1 Lexical tokens 33
Bet 2) “Literals 34
3.1.3 White spaces 37
3.1.4 Comments 38
BZ Data Types 39
3.2.1 Integral data types 39
3.2.2 Floating-point numbers 40
3.2.3. Boolean data types 40
3.3 Variable Declarations 41
3.3.1 Declaring, initializing and using variables 41
3.3.2 Variable types in Java 41
3.3.3. Object reference variables 43
3.3.4 Default values for member variables 44
3.3.5 Initializing local variables of different data types 45
3.3.6 Initializing local reference variables 46
3.4 Wrapper Classes AT
35 Operators and Assignment 48
3.5.1 Operators 48
3.5.2 Assignment 49
3.5.3 Mathematical operators 51
3.5.4 Relational operators 53
3.5.5 Logical operators 55
3.5.6 Bitwise operators 56
3.5.7 Shift operators 56
3.5.8 Ternary If—Else operator 57
3.5.9 Comma operator 58
3.5.10 String operator + 58
3.5.11 Operator precedence 58
3.5.12 Casting operators 59
3.6 Control Structures 60
3.6.1 Block 60
3.6.2 Loop 61
3.6.3 Branching statements 68
Contents ee

a3] Arrays 74
3.7.1 One-dimensional arrays 74
3.7.2 Multi-dimensional arrays 75
3.8 Strings wi
3.8.1 Constructors of String class with character array and string object (2)
3.8.2 Constructors of String class with byte array 78
3.8.3. Methods of the String class aS
39 The StringBuffer Class 82
3.9.1 Constructors of the StringBuffer class 82
Objective type questions 83
Exercises 87
Answers 88

Chapter 4 Java as an OOP Language 89


4.1 Defining Classes 89
4.1.1 Creating instance and class variables 89
4.1.2 Defining methods 90
4.1.3. Knowing this 92
4.1.4 Variable scope and method definitions 94
4.1.5 Passing arguments to methods 96
4.1.6 Class methods 98
4.1.7 Overloading methods 99
4.1.8 Constructor methods 100
4.1.9 Inheritance, polymorphism and abstract classes 104
4.1.10 Overriding methods 108
4.1.11 Finalizer methods js
4.2 Modifiers 113
4.2.1 Controlling access to methods and variables 114
4.2.2 Method protection and inheritance 117
4.2.3 Creating accessor methods lay;
4.2.4 Class variables and methods 119
4.2.5 Finalizing classes, methods and variables 122
4.2.6 Abstract classes and methods 123
4.3 Packages 126
4.3.1 Using packages Wd
4.3.2 Using package and class names in full by
4.3.3. The import command 128
4.3.4 Name conflicts 128
4.3.5 Creating packages 129
4.3.6 Packages and class protection 131
Contents

4.4 Interfaces 133


4.4.1 Interfaces and classes 133
4.4.2 Creating and extending interfaces 133
4.4.3 Other uses of interfaces 139
Objective type questions 139
Exercises 147
Answers 147

Chapter 5 Exception Handling 148

$21 Introduction 148


5.2 Basics of Exception Handling in Java 150
33 Exception Hierarchy 152
5.3.1 Throwable class hierarchy 152
5.4 Constructors and Methods in Throwable Class 153
5.4.1. Constructors 153
5.4.2 Methods 154
5.5 Unchecked and Checked Exceptions is
5.6 Handling Exceptions in Java 155
5.6.1 Try block 156
5.6.2 Catch block 156
5.6.3 Finally block 158
5.6.4 Multiple catch blocks 159
5.6.5 Nested try statements 161
5.6.6 The keyword throw 162
Se, Exception and Inheritance 163
Throwing User-defined Exceptions 165
eye Redirecting and Rethrowing Exceptions 167
5.9.1 Redirecting exceptions using throws 167
5.9.2 Rethrowing an exception 170
Advantages of the Exception-Handling Mechanism wal
Objective type questions 176
Exercises ree
Answers 180

Chapter 6 Multithreading 181


6.1 Introduction: an Overview of Threads 181
6.2 Creating Threads 182
6.2.1 Creating a new thread extending Thread 182
6.2.2 Creating a thread implementing Runnable interface 185
Contents xili

6.2.3 Stopping threads: the join() method 187


6.2.4 Naming a thread 188
6.3 Thread Life-cycle 188
6.3.1 The newborn state 188
6.3.2 The runnable state 188
6.3.3 The running state 189
6.3.4 The dead state 190
6.3.5 The blocked state 190
6.3.6 Manipulating threads 190
6.4 Thread Priorities and Thread Scheduling oz
6.4.1 setPriority and getPriority 192
6.4.2 Time-slicing 192
6.4.3 The scheduler 192
6.5 Thread Synchronization 193
6.5.1 Synchronized methods 194
6.5.2 Synchronized statements 196
6.5.3 Deadlocks 198
6.6 Daemon Threads 198
6.7 Thread Groups 199
6.8 Communication of Threads 201
6.9 Sample Programs 206
Objective type questions 210
Exercises 212
Answers 212

Chapter 7 Files and I/O Streams 213

Lol An overview of I/O Streams 243


fe Java I/O 214
7.2.1. Character streams 214
7.2.2 Byte streams 216
7.2.3. Working with the I/O super-classes Zty
Los File Streams 220
7.4 FileInputStream and FileOutputStream Lie
the; Filter Streams 224
7.5.1 DataInputStream and DataOutputStream Bipos)
7.5.2 PushbackInputStream 227
7.6 RandomAccessFile 228
04 Serialization 230
Objective type questions 253
Exercises 230
Answers 236
Contents

Chapter 8 Applets 237

8.1 Introduction 237


8.2 Java Applications Versus Java Applets 239
8.3 Applet Life-cycle 239
8.3.1 The init() method : } 241
8.3.2 The start() method 241
8.3.3. The stop() method 242
8.3.4 The destroy() method 242
8.3.5 The paint() method 242
8.4 Working with Applets 243
8.4.1 Running the applet using AppletViewer 245
8.4.2 Running the applet using the web browser 246
8.5 The HTML APPLET Tag 248
8.5.1 Attributes in the applet tag. 248
8.5.2 Passing parameters to applets 249
8.6 The java.Applet package 251
8.7 Sample Programs Pa,
Objective type questions Pa
Exercises 261
Answers 261

Chapter 9 Database Handling using JDBC 262

a1 An Overview of DBMS 262


9.1.1 Database operations 263
9.1.2 Database application architectures 263
2192 JDBC Architecture 266
9.2.1 Interfaces in JDBC API 266
9.2.2 Types of database driver 267
9.3 Working with JDBC 267
9.3.1 Accessing a database using JDBC 267
9.3.2 Registering the driver 268
9.3.3 Connecting to the database 268
9.4 Processing Queries 270
9.4.1 The Statement class 271
9.4.2 Accessing rows returned from a query 273
9.4.3 Accessing column data 253
9.4.4 The method PreparedStatement a7
9.4.5 The method CallableStatement 278
9.5 The Transactions Commit and Rollback 279
Contents os

9.6 Handling Exceptions 280


oF Mapping Database Types to Java 281
9.7.1 Java format types 281
9.8 Accessing Metadata 282
9.8.1 Methods in the class ResultSetMetadata 282
9.8.2 The class DatabaseMetadata 283
99 Sample Programs to Handle Databases 284
Objective type questions 294
Exercises 296
Answers 297

Chapter 10 The Abstract Window Toolkit 298


10.1 Introduction 298
10.2 Basic Classes in AWT 299
10.2.1 The class Graphics 299
10.2.2 Colours 299
10.2.3 Font 300
10.3 Drawing with Graphics Class 300
10.4 Class Hierarchy of AWT 301
10.5 Event Handling 302
10.5.1 Adapter classes 304
10.6 AWT Controls 305
10.6.1 Labels 305
10.6.2 Buttons 305
10.6.3 CheckBox 307
10.6.4 CheckboxGroup for creating Radio Buttons 308
10.6.5 Choice control 310
10.6.6 List control 311
10.6.7 TextField control a13
10.6.8 Scroll bars 314
10.7 Layout Managers 2A
10.7.1 The FlowLayout manager 316
10.7.2 The GridLayout manager 316
10.7.3. The BorderLayout manager St?
10.7.4 The CardLayout manager 318
10.8 The Java2D API 319
10.9 Java2D Shapes 319
10.9.1 Texture paint and gradient paint: 323
Objective type questions 327
Exercises BPae
Answers 329
xvi Contents

Chapter 11 Swings 330


11.1 Introduction 330
11.2 The Swing Packages 331
11.3. The Hierarchy of Swing Classes 2
11.3.1 JPopupMenu ; 332
11.3.2 JDesktopPane and JInternalFrame 336
11.4 Advanced Layout Managers 340
11.4.1 The BoxLayout manager 342
11.4.2 The GridBagLayout manager 343
11.5 Additional Swing Components 348
11.5.1 The Jlist class 348
11.5.2 The JcomboBox class Spl
11.5.3 Constructing menus 354
11.5.4 The JTextArea class B59
11.5.5 The JTable control 365
11.5.6 Customizing the frame and its look-and-feel 366
11.5.7 The JToolBar class 372
11.5.8 The JSlider control 375
11.5.9 The JProgressBar class 378
11.5.10 Borders 382
Objective type questions 385
Exercises 387
Answers 387

Chapter12 £Serviets 388

121 Introduction 388


12.1.1 Advantages of servlets 389
12.1.2 Writing servlets 389
12.2 Howto Run Servlets 391
12.2.1 Running HtmlToServlet B92
12.3. The Life-cycle of the Servlet 393
12.3.1 Instantiating and initializing a servlet—the init() method 394
12.3.2 Handling client requests and responses—the service() method 395
12.3.3 Destroying the Servlet—the destroy() method 395
12.4 Servlet API 396
12.4.1 Interfaces 397
12.4.2 Classes 397
12.4.3 The GenericServlet class 397
12.4.4 The HttpServlet class 398
Contents xvii

12.5 Multi-tier Applications using JDBC from a Servlet 404


12.5.1 Writing JOBC/Servlet 404
12.5.2 Asample JDBC/Servlet application 406
12.6 Additional Capabilities of HTTP Servlets 408
12.6.1 Objects of the HttpServletRequest class 409
12.6.2 Objects of the HttpServletResponse class 409
12.6.3 Examples of GET and POST Requests 410
12.7 Session Management 412
12.8 Sample Programs 414
Objective type questions 421
Exercises 423
Answers 424

Chapter 13 Networking and


Remote Method Invocation 425

13.) Introduction to Networking 425


13.2 Understanding Ports 426
13.3. Networking Classes in the JOK 427
13.3.1 Basics of sockets 427
13.3.2 Simple client-server programming 428
13.3.3 Reading from and writing to a socket 429
13.4 — Introduction to RMI 432
13.5 RMI Architecture 433
13.5.1 Proxy layer or stub/skeleton layer 435
13.5.2 Remote reference layer 435
13.5.3. Transport layer 435
13.6 Implementing Remote Class and Interface 435
13.6.1 Programming a client 437
13.6.2 Programming a server 437
13.7. —_Security 439
13.8 Sample Programs 440
Objective type questions 448
Exercises 449
Answers 450

Chapter 14. New Language Features of Java 1.5 451

14.1 Introduction 451


14.2. Generics 452
14.3. The Enhanced for Loop 453
Xvili Contents

14.4 Autoboxing and Unboxing 455


14.5 Type-Safe Enumerations 456
14.6 Variable-Length Arguments 456
14.7. Formatted I/O 457
14.8 Static Import 458
14.9. Metadata (Annotations) ‘ 459
14.10 Sample Programs 460

Index 467
Object Oriented
Programming
Computer programming languages have undergone a dramatic change from being procedure
oriented to object oriented in the last decade. One reason for such a shift in approaches is the
increased usage of software in dealing with problems having a high level of complexity. This and
the need to reuse parts of software in different applications have led to the popularity of object
oriented programming (OOP). This chapter covers the basics of OOP.

g 1.1 Introduction to OOP

In early days, programs were collections of procedures acting on data. A procedure is defined as
a collection of instructions executed in sequential order. Data were independent of the procedures
and programmers have to keep track of functions and the way they modify data. Structured
programming is a simpler way to tackle this situation.
In structured programming, a complex program is broken into sets of smaller, understandable
tasks; however, the drawbacks of structured programming soon became clear. These were, first,
that data and task independency were too hard to maintain. Second, programmers were reinventing
new solutions to old problems. To address these problems, object oriented programming came into
existence. This provides a technique for managing huge complexity, achieving reuse of software
components and coupling data with the tasks that manipulate data.
Object oriented programming, as a concept, was introduced by Xerox Corporation in the early
1970s. The first object oriented language was Smalltalk. The concept of object orientation in
this language did not prove successful for about 10 years because of the limitations of early
computers. Some languages that successfully implemented object oriented programming are
C++, Java and Eiffel. Object oriented programming is thought to be a relatively new concept
in computer science. Contrary to this, all the major concepts such as objects, classes, inheritance
herarchies were developed by researchers of Norwegian Computing Center as part of development
of programming language Simula in the 1960s. Yet the importance of these concepts was slowly
recognized by the developers of Simula.
Object oriented programming deals with things called ‘objects’. Objects are just extremely
functional ways of organizing information. Objects in an OOP language are combinations of code
and data that are treated as a single unit. Each object has a unique name and all references to that
object are made using that name.
2 Object Oriented Programming through Java

Allowing the programmer to write applications that interact with what appear to be physical
objects makes the task of writing computer programs easier.
When an application is being created using OOP, the programmer needs only to remember a
small set of flow-control commands and how to interact with the objects that his/her application uses.
Object oriented programming is built on the concept of reusing code through the development
and maintenance of object libraries. These objects are available for building and maintaining
other applications. Usually, a library contains the code for various functions that are commonly
required during the program development. These libraries can be language-specified or user-
defined. Unlike traditional libraries, OOP languages provide object libraries which contain code
along with the data in the form of objects, in addition to the names and entry points of the code
located within. Objects of an object library are available for building and maintaining other
applications.

a 1.2 Objects and Classes


Objects and classes are the building blocks of OOP. To understand OOP, first we have to know
what objects and classes are.
An object is a programming entity in OOP. It has data components representing the present
state of the object as well as functions (also called methods). Data components are termed
attributes in the context of OOP languages. An area of memory is kept aside to store values for the
attributes when an object is created. Functions describe the behaviour of the object and allow the
other programming entities to interact with the object.

An object contains attributes (variables) and methods (member functions). Attributes


are the data associated with the object and the methods are the functions and code which
operate on the data.

A class is a model to define objects. In other words, an object is said to be an instance of a class.
An object may be real or abstract. That is, objects can model concrete things such as people,
and data entry forms as well as abstractions such as numbers, equations or geometrical concepts.
Consider an example of a class—car. The class car describes all car objects by specifying the
data components and the methods that each can have. Various objects defined in the class car
could be Maruti 800, Zen, Santro, Accent and so on. The class car has various attributes such as
the seating capacity, maximum speed, engine capacity, parking light, current speed and current
position. Typical functions of the car class are to find acceleration and set parking lights on. See
Figures 1.1(a) and (b) for an illustration.
Real-world objects have two characteristics: state and behaviour. For example, consider an
object ball. A ball has particular characteristics such as its diameter, colour and elasticity. Formally,
we say that these characteristics contribute to the ball’s state of being. We also describe a ball by
what it does, such as the fact that it can be thrown, bounced or rolled. These activities define the
ball’s behaviour. Similarly the object car has state (colour, wheels, current gear, number of gears
and so on) and behaviour (braking, changing gears, accelerating, decelerating and so on).
Object Oriented Programming 3

Attributes

seating capacity
speed
engine capacity
Attributes parking light
current speed
current position

Methods
Methods

acceleration();
parking();
turning();

(a) (b)
z Fig. 1.1 (a) An object; (b) example of object car.

Software objects are modelled after real-world objects in that they too have state and behaviour.
Attributes define the state of the object and methods define the behaviour of the object. That is, a
software object maintains its state in one or more attributes. Attributes can have different values at
different instances of time; however, values of a particular attribute must have the same data type.
An attribute/variable is an item of data named by an identifier, and a software object implements
its behaviour with methods. A method is a function/sub-routine associated with an object.
The state of an object and its behaviours work together. For example, how high a ball bounces
depends on its elasticity. An object’s behaviour often modifies its state. For example, when a ball
is rolled, its position changes.
An object must also have a unique identity that distinguishes it from all other objects. Two
objects can have the same data types of attributes with the same names, and those attributes can
have the same values. Therefore two objects could have the same state. There must be a way of
distinguishing the two objects and that is done by using an object’s name. In a program, to define
an object we need a class.

A class is a model or pattern from which an object is created. In other words, a class is a
special module that defines an object.

A class defines the data types of attribute that will be held in an object, and defines code for
the methods. After a class was defined, an object can be created from it. The process of creating
an object from a class is called instantiation. Every object is an instance of a particular class.
4 Object Oriented Programming through Java

Defining a class is having a name, a set of attributes and a set of methods defined. The attributes
will not have any values associated with them when a class is defined; however, when an object
is created from this class, the attributes of this object will have values. The values of the attributes
can be accessed and/or modified by the methods of that class and cannot be accessed or modified
by the objects of the other class. :
The definition of a class must not be confused with that of an object. A class is the outline
for an object. But a class is not an object any more than a blueprintis. We introduce the notion of
data types, which makes easy to understand the difference between objects and classes. Consider
a data type integer. We can declare variables to be of type integer. For example, in C, we can do
this with the statement
int 1a);

This statement defines two variables i and j of type integer. When this statement is executed, the
two variables are created. Similarly, an object can be defined by a class. That is, a class is similar to
a data type (data structure) and an object is like a variable created from some class. In other words,
a class defines a type and an object is a particular instance of the class. Suppose Circle is a class,
the objects A and B can be created from that class, as in C++, where A and B may be circles of
different diameters.
Circle A, B;

An object can be viewed from two perspectives. The first is useful during design and
implementation of the object. We have to define the attributes that will be held in the object and
write the program code for the methods that make the object useful. The second comes in when
making use of the services of an object that was already created. When designing a solution to a
large problem, we should know only the services that an object provides rather than the details
of how the services are accomplished. That is, from the second point of view, an object is a black
box. It is a part of a system whose inner workings and structure are currently hidden. The rest of
the system only interacts with the object through a well-defined set of services (called messages)
that it provides.
In OOP, objects communicate with one another by sending and receiving information using
messages. For an object, a message is a request for execution of a method. When a request is made
to an object, it invokes the specified method in the receiving object, then the receiving object
responds by generating the desired result. Message passing involves specifying the name of the
object, the name of the method and any information that needs to be sent.

a 1.3 Characteristics of OOP


At the heart of OOP are three main characteristics. These are the features from which the
advantages of using OOP are born.
¢ Encapsulation
¢ Inheritance
* Polymorphism
Object Oriented Programming 5

These characteristics differentiate object oriented programming from the traditional procedural
programming model. They are now examined in more detail.

1.3.1 Encapsulation

An object encapsulates the methods and data that are contained inside it. The rest of the system
interacts with an object only through a well-defined set of services that it provides.

The concept of sealing data and methods that operate on the data into an object (a single
unit) is known as encapsulation.

Encapsulation of data and methods within an object implies that it should be self-governing,
which means that the attributes contained in an object should only be modified within the object.
Only the methods within an object should have access to the attributes in that object. If the state
of an object needs be to changed, then there should be some service methods available that
accomplish the change. That is, one should never be able to access and change the values of an
object’s attributes directly from outside.
For example, embedding the attributes and methods defined for car in a single class car is
referred to as encapsulation (see Figure 1.1(b)). The methods described in the car class can only
modify/access the attributes defined in its class. Suppose, Zen is an object of car class, to set the
parking light of Zen, the attribute parking light can be set using the method set_parking_light_on;
however, other objects of the same class such as Maruti 800 or objects of any other class cannot
access/modify the value of parking_light for Zen object.
Encapsulation helps in building better, structured and more readable programs.

1.3.1.1 Abstraction via encapsulation

Encapsulation facilitates abstraction. A software object is an abstract entity, in that we view it


from outside without concerning ourselves with the details of how it works on the inside. For
example, we do not need to understand the internal workings of the gears of a car to use it, we
only need to know how to make it work. Because of this the source code for an object can be
written and maintained independently of the source code for other objects. Also, an object can be
easily passed around in the system.
Since, an object is a self-contained entity in a program, it can be referenced at different parts
of the program wherever it is required. This feature enhances the modularity of the program. That
is, the program consists of several modules, and if there are problems with any module, they can
be addressed independently. Also, these modules can interact with each other without having
to know the internal implementation of the other. Dividing a program into modules is called
modularity; not having to know the internal implementation of a module is called abstraction.
Hence, the feature of ‘abstraction’ facilitates a programmer to do ‘modular’ programming.
‘6 Object Oriented Programming through Java

1.3.1.2 Data hiding

Encapsulation provides the hiding of data/information. It prevents users from seeing the internal
workings of an object. The main reason for doing this is to protect data that should not be
manipulated by the user. This makes the code more reliable and reusable.
An object has a public interface that other objects can use to communicate with it. The object
can maintain private information and methods that can be changed at any time without affecting
other objects that depend on it.
Every class can hide some of its parts. For example, ifa part of code is called only by methods
of that class, it can be made a private method, that is, invisible from outside that class.
Every element (field or method) of one class can have one of the three levels of visibility:
public, private and protected.
¢ Public elements are completely visible from outside the class. They form the interface with
the outside world.
¢ Private elements are visible only to methods of the class itself.
¢ Protected elements are something between public and private. To the outside world, they
act as private elements, but they are completely visible to inherited child classes (these are
discussed later)—they have public behaviour for these classes.
Some benefits of encapsulation are the following:
¢ Improves program reliability
* Reduces maintenance
¢ Lends reusability
¢ Facilitates information hiding
¢ Improves modularity
¢ Makes coding easier (This allows for inefficient codes to be optimized later.)

1.3.2 Inheritance

Inheritance is the feature of OOP by which the functionality of a class, called the parent or base
class, can be extended by creating another class, called the child or derived class, which inherits
some or all of the features of the parent class. The derived class has its own methods apart from the
methods of base class and thus extending the functionality. This is the key for code-reusability.

Inheritance is the process of creating a new class from previously defined classes.

When a derived class inherits from the base class, it will contain all the attributes and methods
of the base class but adds new characteristics of its own. Any changes that are made to base
classes are propagated to all derived classes that inherit from them, unless explicitly overridden.
Changes to a base could fix or break an application.
Object Oriented Programming T

Consider the example of the car class. Suppose we want to create a new class called Maruti.
We know that a Maruti is a car so we can derive this new class from our base car class. Some of
the data for this new class may be size and mileage and a function would be engine. But since
this is a derived class, we can also have access to the base class functions, accelerations and
deceleration, plus the data of the base class type, colour and wheels.
Thus, inheritance can reduce the amount of coding by letting any derived class use the base
class’s functionality when it needs to, thus simplifying implementation of similar classes and
structures. In addition, the derived class is compatible with the base class, and can be used in place
of the base class. This allows a system to override any of the base class functionality it wants and
use the new objects where the base class would be used, thus adapting it to its own needs.
Derived classes may be formed in many ways. They can be derived from a single base class,
or they can be formed from different parent classes.
When a class is derived from only one base class the process is called single inheritance.
When a class is derived from more than one base class the process is called multiple inheritance.
Multiple inheritance is used to combine two or more existing classes.
Inheritance is often shown diagrammatically in terms of an inheritance hierarchy or inheritance
tree as shown in Figure. 1.2. Note that the arrowhead points towards the base class to indicate that
the child class is derived from it. In single inheritance the inheritance graph is a tree, whereas in
multiple inheritance the inheritance graph is a directed acyclic graph (DAG).
Figure 1.3 is an example of a multiple-inheritance graph.

Base Class Parent Class

Derived Class Child Class

(a) (b)

A Fig. 1.2 (a) Inheritance tree; (b) an example of single inheritance.

Base Class 2 Base Class 2

Derived Class

(a) (b)

ce.
Fig. 1.3 (a) Multiple inheritance graph; (b) an example of multiple inheritan
8 Object Oriented Programming through Java

The advantages of using inheritance are the following:

¢ — Increased productivity
¢ Reduced maintenance
° Standardization

The major drawback of inheritance is added overhead. This is explained below:

¢ An user must know changes in the methods of base class before using the derived class
objects.
¢ Though the derived class objects may not require all the functionalities of a base class,
the derived class implements all the methods of base class. This increases the amount of
memory required for execution of the program.
e Since common functionalities exist in the base class, there is an execution overhead for
derived class due to the implementation of base class methods when compared to having
the functionalities in a single class itself. In the case of a chain of inheritances, the execution
overhead may increase further.

1.3.3 Polymorphism

Polymorphism allows an entity (for example, an attribute, function or object) to take a variety of
representations. It refers to the ability of an object to respond differently to the same message.
The advantage of this property is that the behaviour of an object varies depending on the
message passed to it without worrying about the way the kind of message was passed. That is,
an operation on an object may exhibit different behaviours in different situations. The behaviour
depends on the data types and number of parameters used in the operation.
For OOP languages, polymorphism ensures reusability of higher level abstractions. This
feature is also helpful in the implementations of inheritance where some base class behaviour
needed to be overridden. Moreover, polymorphism facilitates describing variables that may refer,
at run-time, to objects of different classes.

1.3.3.1 Overloading

Overloading is one kind of polymorphism. In OOP, there are two types of overloading: operator
overloading and function overloading.

Operator overloading Operator overloading is the ability to use an operator on different


argument types. For example, the operator ‘+’ is used to add either integers or floating point
numbers. Another example is “—’, which is used either negate an expression or to return the
difference between two expressions. In addition, an operator can be overloaded on objects.
Take an object complex number. We can add two complex numbers by overloading the
operators “+’ and ‘=’, using the statement c3 = cl + c2, where cl, c2 and c3 are values of the
complex number type.
Object Oriented Programming 9

Another example of operator overloading is that an addition sign (+) can be used to specify
addition of two numbers (say, 200 + 6 = 206) or concatenation of two strings (say ‘200’ +
‘6’
= *2006’).
Java does not support user-defined operator overloading.

Function overloading Function overloading is the ability to access different implementations


of functions using the same name.
Consider an example that displays the current date. Usually, the date is represented in two
forms:
e Asa string: December 20, 2005
¢ Asa triplet: (day, month, year): 20, 12, 2005
It is easier for a programmer if same function name can perform one of the above tasks
depending on the user requirements. This can be achieved using function overloading by writing
two different functions (methods) bearing same name as given below:
Printdate (Sting Str) {....... }
Printdate(int dd, int mm, int yyyy) {...}
Here, the first Printdate function takes one string parameter as argument and the second
function takes three integer parameters as arguments. Based on the data types of the arguments
passed in a message, the corresponding function is invoked. Thus, two or more functions may
have the same name, so long as the parameter types or number of parameters are sufficiently
different enough to distinguish which function is intended. This feature is not allowed
in procedural languages, as two functions cannot have same name. A function may not be
overloaded on the basis of its return type. In Java, function overloading is referred to as ‘method
overloading’.
There are two types of function overloading: early binding and late binding.
¢ Early Binding This allows us to have two functions in the same class that have the
same name (function name) but with different number of parameters or different data
types of parameters passed to it. The Printdate function described above is an example
of early binding. Early binding takes place during compile time.
° Late Binding This allows us to have functions with same name in base and derived
classes. But the derived class function will override the base class function. Consider the
example of geometric shape and its inheritance tree, as shown in Figure 1.4. We want
to draw and fill the different shapes given in the figure. These two operations differ with
respect to shape of the object and hence different functions have to be written as shown in
Figure 1.5. Here, the base class functions draw( ) and fill( ) are overridden by the derived
class functions. So, the function to be executed is selected dynamically during run-time,
based on the shape object referred. This process of choosing the function dynamically at
_ run-time is referred to as late binding.
10 Object Oriented Programming through Java

Geometric shape

Rounded object

Ellipse

| Fig. 1.4 An inheritance tree of geometric shape.

Geometric shape

Draw()
Fill()

Rounded object

Draw() Draw()
Fill() Fill()

Circle Ellipse

Draw() Draw()
Fill() Fill()

Fig. 1.5 An inheritance tree of geometric shape with functions.

The main benefit of polymorphism is it improves flexibility.


Overloading is not unique to OOP, it exists in procedure oriented programming languages
also, such as C, to a limited extent. In C, we can use the operator ‘+’ for two integers as well as
for floating point numbers. Similarly, the functions printf and scanf can have different number of
arguments with different types.
Object Oriented Programming ‘1

q 1.4 Difference between OOP and Procedure Oriented


Programming
Now that we know the basic concepts in OOP, we are in a position to compare it with classical
procedure oriented programming.
In classical procedural (or structural) programming, there are techniques to write a code that
handles some general task The most important techniques of that kind are functions (procedures
or sub-routines). The large program is partitioned into functions that each perform a specific
task. The main program calls these functions, which in turn may call other functions. The major
concern of this programming is with respect to the data.
Data are passed around from one non-member function to another and are available
everywhere throughout the large program. This allows the user to access the data directly, alter
it from several points in the program and inadvertently introduce mistakes. If one programmer
changes the representation of the data in the computer’s memory by rearranging fields within
a structure (record), other functions in the program may need to be rewritten and must then be
retested to account for this change. That means the data are not well protected in procedure
oriented programming. Though local variables in a function can be accessed within the function,
they are not useful if they must be accessed by different functions.
Tn contrast, OOP safely encapsulates collections of functions (called methods) with the data
they manipulate. In other words, the data can only be manipulated by its own functions. This
feature protects the data from rest of the program.
Though the concepts of object oriented programming are different from procedural oriented
programming, structured programming constructs are still used in OOP especially in the coding
of methods.

q 1.5 Summary

As stated earlier, the principles of encapsulation, inheritance and polymorphism form strong
structures and define the major benefits and drawbacks of OOP. Let us take a look at these
aspects.

1.5.1 Benefits of OOP

* Code reusability New objects can be derived from old objects, allowing for improvement
and refinement of the code at each stage and also preserving parts of the code for other
programs. This is used to develop many class libraries using class codes that have already
been written, for example, Microsoft Foundation Classes (MFC).
* Code Modularity Everything in OOP is an object; these objects can be interchanged or
removed to meet the users’ needs.
¢ Easier maintenance Inheritance usually reduces maintenance because of the domino
effect it has on derived classes when a change is made in a base class.
12 Object Oriented Programming through Java

Design stability Once a stable base class has been developed, the new classes that are
derived may have fewer less errors and bugs.
Improved communication between developers and users Objects can be broken down
into real life entities, hence it is easier it communicate ideas.
Seamless transition from design to implementation This is mainly because communica-
tions are improved. a

1.5.2 Drawbacks of OOP

Execution overhead Once a derived class is initiated all the data and functions from the
base classes are carried along with it. Some of these, or even most of it, may not be used.
Derived classes can be very complex because of inheritnce and polymorphism.
Abstraction may lead to performance degradation.

1.5.3 Challenges of OOP

High learning curve OOP is different from traditiona! programming. We must develop
strong base classes and understand the functionality of class libraries before we can take
advantages from it.
¢ Difficulty in establishing base classes A good foundation must be created before you
derive other classes. Base classes have to be generic enough to meet the needs of your
application and any future upgrades to that application.

Objective type questions

are combination of code and data that are treated as a single unit.
. In objects, the behaviour of the real-world entities is represented by
. In objects, _______ define the state of an object.

is a model or blue-print from which an object is created.


. Binding the data to methods of an object is called

provides the mechanism of ‘One name but different implementations’.


A method is used to assign values to private instance variables of a class.
. Inheritance enables _________ which saves time in development and encourages using
previously proven and high quality software components.
Object Oriented Programming 13

. A method call resolved at compile-time is referred to as and a method call


resolved at run-time is called

10. If class A inherits class B, Class A is called class and class B is called
class.

iv Object oriented programming was motivated to address which one of these major
concerns in software development:
a. Modularity.
b. Symbolic names in assembly language programs.
c. Large memory requirements of Procedural programming.
d. Reusability of code.
12. Which of the following is the process of hiding the internal parts of an object implementation
and allowing access to that object only through a defined interface.
a. Polymorphism b. Encapsulation. c. Inheritance. d. Over-riding.
13. Which elements of the class provide interface to the outside world.
a. protected. b. public. c. private. d. none of the above.
14. Which elements of parent class do the derived classes not inherit?
a. protected. b. public. c. private. d. none of the above.
15. Data hiding makes the data more reliable and reusable (True/False).
16. Ifaclass is derived by another class then the base class cannot be used independently (True/
False)

Exercises
1. What is an OOP? What is the difference between Procedural language and OOPs?

2. Explain Encapsulation, Inheritance and Polymorphism.


3. Describe the characteristics of object oriented programming concepts.

4. Discuss the advantages and drawbacks of object oriented programming.


5. Suppose we are developing software to administrate the activities of a college, such as fee
deposits, library, student and staff database and marks. Identify the objects/classes in the
system and draw the Inheritance hierarchies that exist in the system.
6. Complete the inheritance tree shown in Figure 1.4 by incorporating other geometric shapes
like sphere, cylinder, hexagon, isosceles triangle and so on. Also, describe more functions
(for example, finding area) which can be incorporated in each class and mention the methods
that are to be overridden.
14 Object Oriented Programming through Java

Answers

1. Object 2. Methods 33 datamembers or 4. class


data elements
5. Encapsulation 6. Polymorphism Th class 8. software reusability
9. early binding, 10. derived, base ips d igen Bad
late binding
20 14. c 13; True 16. False
Introduction to
Java Programming

Java is an object oriented programming language that also provides run-time environment. This
chapter gives a brief introduction to Java and what makes it more powerful than other object
oriented programming languages. It also gives an overview of arrays, methods and structures in
Java and a summary on Java applications and applets, so as to familiarize the reader with Java
programming. It is an introduction to Java programming concepts meant for beginners, while
experienced programmers would find it helpful in revising their skills.

q 2.1 Introduction

A computer program is usually written using a programming language (such as C, C++ or Java).
It can be defined as follows:

A program is a series of instructions (usually long and complex) that are carried out (or
executed, or run) by a computer.

These instructions define what the program does, whether it is a word processor, spreadsheet,
game or any other kind of program.
Programming can fall into the category of application programming or systems programming.
Application programming is a programming process that is aimed at developing an application
(such as banking applications, railway reservation application and so on) to be used by people
(end users). Systems programming, on the other hand, is the activity of writing, amending or
extending the operating system, which is a program that runs on the computer hardware in order
to allow other applications to be run.

2.1.1 Overview of Java technology

Java technology is simultaneously a programming language and a platform.


~ 46 Object Oriented Programming through Java

2.1.1.1 Java as a programming language

Java is a general-purpose high-level object oriented programming language that provides the
following characteristics:
¢ Simple ¢ Object oriented
e Interpreted e Architecture-neutral
¢ Platform independent ¢ Multithread
e Dynamic ¢ High-performance
¢ Distributed ¢ Robust
e Secure
Usually, a programming language requires either a compiler or an interpreter to translate a
code written in high-level programming language (source code) into its machine language (object
code) equivalent. But, to run a Java program, Java uses a combination of compiler and interpreter.
The Java compiler translates the Java program into an intermediate code called Java byte code.
A Java interpreter is used to run the compiled Java byte code. This allows Java programs to run
on different platforms. A compiled Java byte code can be executed on any computer platform on
which the Java interpreter is installed. For each type of computer, a different Java interpreter is
required to interpret the Java byte code. This is illustrated in Figure. 2.1.
Java is a strongly typed language. That means, that every variable (or expression) has a type
associated with it and the type is known at the time of compilation. Thus, in Java, data type
conversions do not take place implicitly.
There are three kinds of Java program:
¢ Applications These are stand-alone programs that run on a computer.
* Applets These are programs that run on a web browser. Appletviewer is provided to
ensure that these programs run without a web browser.
¢ Servlets These are programs that run at the server side

2.1.1.2 Java as a platform

A software and/or hardware environment in which a program runs is referred to as a ‘platform’.


The Java platform is a software platform that is compatible with and/or executes on platforms
based on different hardwares. The Java run-time environment is shown in Figure 2.2. Figure 2.3
shows the Java programming platform.

Java Java
source code byte code Interpreter
(Sample.java) (Sample.class)

Be Fig. 2.1 Java as a compiler and interpreter.


Introduction to Java Programming 47

Source code

Source code

Virtual machine Virtual machine Virtual machine


(Interpreter) (Interpreter) (Interpreter)

Object code Object code Object code Object code

Operating system
Oper Operating system Operating system Operating system
(Unix, Linux, Windows etc) (e.g. Unix) (e.g. Unix) (e.g. Windows)

(a) (b)
S Fig. 2.2 Run-time environment for (a) a typical program; (b) Java.

Java platform Java API

hardware platform

Pe Fig. 2.3 Java programming platform.

The Java platform consists of the Java Virtual Machine and the Java Application Programming
Interface. These two important components of the Java platform can be analysed and described
as follows:
Java Virtual Machine (JVM) It is an interpreter, which receives bytecode files and translates
them into machine language (object code) instructions. The JVM is specific to each operating
system (for example, Unix, Linux, Windows).
418 Object Oriented Programming through Java

Java Application Programming Interface(JavaAPI) This isacollection of software components


that offer various useful functions. The API is grouped in the form of packages (libraries) of
interrelated classes as well as interfaces.

2.1.2 A short history of the development of Java

¢ Java is a result of the efforts of programmers in the early 1990s to develop a portable,
secure and scalable language to be used for communication between electronic devices.
¢ A team of programmers led by James Gosling of Sun Microsystems developed the first
version of Java. This version was called Oak. Java language was meant for programming
the embedded systems in consumer electronics devices.
¢ Since the Oak trademark was already registered with some other organization, Sun
Microsystems renamed the language Java, in January 1995.
¢ During the period when Oak was being developed, the computer world witnessed the
emergence of the Internet. As Internet usage became widespread, the need for a portable,
secure programming language increased. Java fit the bill perfectly. Initially developed for use
on different electronic devices, the language was later adapted for Internet programming.
¢ Java met all the requirements specified for web-based applications as it can be used to write
platform-independent code.
¢ In 1995, Sun Microsystems released the first version of the Java Development Kit (JDK)
and HotJava, a Java-enabled browser. HotJava was capable of running Java applications
in the form of Java Applets embedded in web pages, a feature since taken up by browsers
from Microsoft and Netscape.
¢ Java is often described as the World Wide Web (www) programming language. From the
second half of the 1990s, the popularity of Java increased considerably.
An important consequence of the evolution of Java is that it has grown into a full-scale
development system, quite capable of being used for developing large applications that exist
outside of the web (Internet) environment (that is, all kinds of program that run on a PC), including
those that make extensive use of networking to enable communication between programs.
Sun Microsystems are now working to further refine and develop Java language. In addition,
they are also working on other Java tools and applications. Prominent among these are the
following:
* Java Beans—the Java object component technology.
* JavaServer—a complete web server application written in Java, supporting servlets.
¢ JDBC—Java Database Connectivity, providing a Java-based interface to SQL databases.
* Java Workshop—a Java programming environment for developing Java programs which is
itself written in Java.
To get the latest updates on other Java tools and applications, readers can refer to the website
of Sun Microsystems—http://www.sun.com.
Introduction to Java Programming 19

2.1.3. Java as a new paradigm in programming

There are a number of other factors that are attributed to the rise in popularity of Java.
These
include the following:
* Familiarity of Java as a programming language to users of other popular languages,
notably C++ and Smalltalk: due to this factor, users find it simple and easy to relate and
comprehend.
* The Java development kit is offered free of cost: this factor allows potential users to try out
the language with minimal start-up cost.
* Its availability: Java is offered as freely downloadable software from the Sun Microsystems
website. The software is also available on other websites.
* Finally, its timing: Java gained popularity as it emerged at the right time—when the Internet
was in its nascent stage and was all set to grow in popularity.

q 2.2 Features of Java

Java has unrivalled features that make it popular as a programming language. It is simple, is
highly robust, secure, platform-independent and, hence, portable. These features of Java are given
below:

1. Javais asimple and object orientedlanguage Javais based on object oriented concepts. This
makes it familiar to programmers using C++ and other object oriented programming languages.
It is attuned to current software practices.
Java gives programmers access to existing libraries of tested objects that provide functionality
ranging from basic data types through input/output and network interfaces to graphical user
interface toolkits. These libraries can also be extended to provide new behaviour.
2. Javaishighlysecure Javaallows programmers to develop (or create) highly reliable software
applications. It provides extensive compile-time checking, followed by a second level of run-time
checking. The features of Java guide programmers towards reliable programming practices.
Using Java makes memory management extremely simple. In Java, objects are created with
the operator new. There are no explicit programmer-defined pointer data types and no pointer
arithmetic. At the same time, garbage collection is automatic. This simple memory management
model eliminates entire classes of programming errors that haunt C and C++ programmers.
When a pointer goes out of scope, a garbage collector usually relies on the compiler to
deallocate the object the pointer points to. Most of C and C++ compilers do not provide garbage-
collection mechanisms and the programmer has to explicitly specify the free() in C or delete
in C++. In large and complex programs, improper use of references to memory may lead to
errors during execution. In Java, when an object is no longer required, the Java garbage collector
automatically reclaims the memory occupied by the object. The memory allocated to an object is
not deallocated explicitly when it is used.
~20 Object Oriented Programming through Java

Java technology is designed to operate in distributed environments, which means that security is
of paramount importance. The security features of Java allow programmers to design applications
that are extremely difficult to tamper with. In network environments, applications written in Java
are safe from intrusion by unauthorized codes attempting to get behind the scene and create
viruses or invade file systems.
3. Java is architecture neutral and portable 1n heterogeneous network environments, appli-
cations must be capable of being executed on a variety of hardware architectures and operating
systems. In addition, the applications should be able to interoperate with multiple programming
language interfaces. Java supports applications that are deployed in heterogeneous network en-
vironments. To accommodate diversity of operating environments, the Java compiler generates a
byte code.
Unlike a C compiler, the Java compiler does not produce a native executable code for any
particular machine. Instead it produces a special format called the byte code which is an architec-
ture-neutral intermediate format designed to transport the code efficiently to multiple hardware
and software platforms. It does not contain any machine- or hardware-related information.
Using the byte code, Java solves the problem of platform-independence. The Java byte code
written in hexadecimal characters, byte by byte, looks like this:
CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08

Byte codes are precisely defined and remain the same for all platforms. Java programs that have
been compiled into byte codes still need an interpreter to execute them on any given platform. The
interpreter reads the byte code and translates it into the native language of the host machine. See
Figure 2.4 for an illustration of the process of compiling and running a Java program.
Understanding the byte code Since the byte code is completely platform-independent, only
the interpreter and a few native libraries need to be ported to get Java run on a new computer or
operating system. The rest of the run-time environment, including the compiler and most of the
class libraries, are written in Java.

Java byte code Compile-time


Environment

Interpreter

Run-time system Bytecode


oy PENS Run-time
verifier loader .
Environment
Code generator

Operating system

Fe Fig. 2.4 Complete Java environment.


Introduction to Java Programming 24 ~*~

Use of the interpreter in Java technology solves both the binary distribution problem and the
version problem. This ensures that the same Java programming language byte codes will run on
any platform.
Java technology takes portability a stage further by being strict in its definition of the basic
language. Java technology specifies the sizes of its basic data types and the behaviour of its
arithmetic operators. All programs are the same on every platform—there are no data type
incompatibilities across hardware and software architectures. To get an idea of the variety of
machines and platforms where a Java byte code may be executed, see Figure 2.5.
The architecture-neutral and portable language platform of Java is known as the Java Virtual
Machine (JVM). The JVM is the specification of an abstract machine for which the Java
programming language compilers can generate codes. Implementing the JVM on new architectures
is a relatively straightforward task as long as the target platform meets basic requirements such as
support for multithreading and other such requirements.
4. Java shows a high performance Higher performance is ensured by Java by adopting a
scheme in which the interpreter runs/executes at full speed without needing to check the run-time
environment. The automatic garbage collector runs as a low-priority background thread, ensuring
a high probability that memory is available when required, leading to better performance.
5. Java is interpreted, threaded and dynamic The Java interpreter executes the Java byte code
directly on any machine to which the interpreter and run-time system have been ported. The
multithreading capability of Java provides the means to build applications with many concurrent
threads of activity. Multithreading thus results in a high degree of interactivity for the end user.
Java supports multithreading at the language level which results in asynchronous behaviour of
the program. This is discussed in detail in chapter 6.
The language library provides the thread class, and the run-time system provides monitor and
condition lock primitives. At the library level, moreover, Java technology’s high-level system
libraries have been written to be thread-safe and the functionality provided by the libraries is
available without conflict to multiple concurrent threads of execution.
While the Java compiler is strict in its compile-time static checking, the language and run-time
system are dynamic in their linking stages. Classes are linked only as needed. New code modules
can be linked in on demand from a variety of sources, even from sources across a network.

Architecture-neutral Platform independent


(Hardware) (Operating systems)

gi Fig. 2.5 Applicability of the Java byte code.


22 Object Oriented Programming through Java

6. Java is dynamically linked Java does not have an explicit link phase. The Java source code
is divided into .java files, roughly one per each class. The compiler compiles these into .class files
containing byte code. Each .java file generally produces exactly one .class file.
The compiler searches the current directory and directories specified in the CLASSPATH
environment variable to find other classes explicitly referenced by name in each source code file.
If the file that is being compiled depends on other, non-compiled files, the compiler will try to find
them and compile them as well. The compiler handles circular dependencies as well as methods
that are used before they are declared. It also determines whether a source code file has changed
since the last time it was compiled.
More importantly, classes that were unknown to a program when it was compiled can still be
loaded at run-time. For example, a web browser can load applets of differing classes that it has
never seen before without recompilation.
Furthermore, Java .class files tend to be quite small, a few kilobytes at most. It is not necessary
to link in large run-time libraries to produce a (non-native) executable. Instead the necessary
classes are loaded from the user’s CLASSPATH.
7. Other features of Java Javahas no pointers. Java programs cannot access arbitrary addresses
in memory. All memory access is handled behind the scenes by the (presumably) trusted run-time
environment. Java provides automatic memory allocation and de-allocation.

& 2.3 Comparing Java and Other Languages


The best way to describe a computer language is to compare its characteristics with those of other
languages. The major features in which Java differs from other languages are listed below:
¢ Java is similar to C and C++ but is strongly typed (that is, every identifier must have a type)
like Pascal or Ada.
° Java is dynamically linked which means that it does not look for a sub-program until it is
called. This results in smaller programs than are possible with statically linked programs
and permits more efficient transfers of code over the Internet.
¢ Java is case-sensitive, therefore care should be taken in naming fields, identifiers and other
attributes.
¢ Java does not support pointers. It does not permit the direct manipulation of addresses
(results in safer programs).
° Java allows single inheritance (that is instantiation of a child class having properties of only
one parent class) but prevents multiple inheritance. Java permits multi-level inheritance,
however. Multiple inheritance can be achieved in Java through interfaces.
* Java is a compiled and interpreted language, which results in faster applications and
provides more security for the source code.
Introduction to Java Programming 23

q 2.4 Applications and Applets


Typically, Java programs are compiled into applets or applications. Applications are stand-
alone programs executed by a virtual machine, while applets are intended to be loaded into and
interpreted by a browser such as Netscape or Internet Explorer. Applets are more complex than
applications because they interact with the current environment of the browser, while applications
are more like standard programs. Applets are discussed in detail in chapter 10.
Java has no pointer types and presents a computation model that guarantees safety. Thus, when
an user executes a Java application or applet from an untrusted source, he or she can be assured
that the Java program will not use the memory in unknown or perhaps malignant manner.
Moreover, the popularity of Java code distribution has come about because it is portable.
Unlike source code, byte code can be distributed. When an application has to be given to multiple
users working on different platforms, the Java byte code can be distributed instead of the source
code. A byte code cannot be modified by a programmer this limits software piracy.

2.4.1 Simple applications using Java

A clear understanding of the above-mentioned features can be gained by writing a simple program
using Java. Program 2.1 illustrates how to print a sentence. The labels indicate parts of the
program.

a Program 2.1 Asimple Java program.

class StartProgram Class declaration

{ Start of program block

// Comments

public static void main(String args[ ])

{
System.out.printin (“This is a simple java program.”);

} End of program block

The above program declares a class named StartProgram. In this class a method called main()
is defined. In this method a single method is invocated that displays the string “This is a simple
java program.’ This string is displayed on the console when the program is executed. Output is
achieved by invoking the printIn method of the object out. The object out is a class variable in the
class System (various classes in Java are described later) that performs output operations on files.
©" 24 Object Oriented Programming through Java

|
C:> javac StartProgram.java

|
Java Compiler

is Fig. 2.6 Compiling a Java program.

Class File

C:> javac StartProgram.java

Java interpreter

This is simple java program Output Generated

B Fig. 2.7 Invoking the Java interpreter.

2.4.1.1 Compiling and running a Java program

A simple program such as Program 2.1 is usually written using notepad (or any other compatible
editor) and saved with the extension java. The name of the program should match the name of
the class. In the case of Program 2.1, the program name would be StartProgram.java (as the class
name declared within the program is StartProgram). The Java compiler is used to compile the
program. The Java compiler is offered with the Java development kit, as shown in Figure 2.6.
On compiling the program a class file is created, that is, StartProgram.class. For the purpose
of executing (running) the class file, Java provides an interpreter (java). This can be invoked as
shown in Figure 2.7.

2.4.2 Other applications and applets

Look at Program 2.2.


Introduction to Java Programming 25 ~~

q Program 2.2 Calculating the sum of two integers.

import java.io.*; ———»


class FirstJavaProgram ———»

public static void main(String[ ] args) throws IOException

oe
ee nec isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

System.out.print(“Enter First Integer:”);

int a = Integer.parselnt(br.readLine());

System.out.print(“Enter Second Integer:”);


int b = Integer.parselnt(br.readLine());
System.out.print(“Sum:’+(a+b));
}

Output:

Enter First Integer: 23


Enter Second Integer: 45
Sum: 68

Program 2.2 reads two integer numbers and gives their sum. Java provides the I/O (input/
output) package to conduct input and output operations. This package has to be imported in any
Java program that undertakes I/O operations.
In Program 2.2, I/O streams (this topic is given indepth coverage in chapter 7) are used to
perform console operations. System.in returns the bytes from console, which is wrapped by the
InputStreamReader, which converts bytes to characters. BufferedReader is used to buffer the
characters.
The readLine() method on the BufferedReader will return the data String upto the carriage
return. This method is used to read data from the console. By using the method Integer.parselnt()
26 Object Oriented Programming through Java

the string data are converted into the integer values. The data entered are added and the output is
directed to console using the System.out.print() method.
Look at Program 2.3, which is a simple applet program:

a Program 2.3 Asimple applet program.

import java.applet.*;
public class StartApplet extends Applet
{
String message = “ Applet program.”;
6099
String message1 :

public void Start()


{
System.out.println(message);
System.out.println(message 1);
}
public void init()
{
StartApplet Text;
Text = new StartApplet();
Text. message1 =“Writing the message.”;
Text.Start();

ES
In Program 2.3, the line
import java.applet.*;
implies that the standard class Applet should be imported before writing an applet program. This
would ensure that all the features of the class Applet can be accessed by the program (child
class). Another thing to note is that any applet should extend the class Applet. This ensures that
StartApplet would be a child class of the class Applet (in other words, StartApplet inherits the
methods and objects in Applet).
In Program 2.3, two String types message and message1 are defined. These two types would
be utilized by the methods Start() and init().
The method Start() outputs two lines of text to the default system output that is the DOS
window.
The method init() is the main executable part of a Java program when StartApplet is run as an
applet. The init() method instantiates the class Text and replaces the empty string in message
with ‘Writing the message,’ and then calls the method Start to print the two lines of text.
Introduction to Java Programming 27

Stand-alone applications written in Java have the main method. Not being stand-alone
applications, applets and servlets have no main method.
Stand-alone applications are programs that are written and run on a stand-alone computer.
When a stand-alone Java program is executed, the Java compiler searches for a class which has
the same name as the name given to the program file, and then finds the main method in this class.
On the other hand, applets and servlets are useful to work in a web environment. These programs
are placed inside a web page that is usually written in HTML (Hyper Text Markup Language).
The applet/servlet is executed through a browser and the browser handles the starting point of the
execution. Applets can also be executed through appletviewer, which is a software provided by
the Java environment to run applets.
After the program StartApplet.java is compiled, a HTML document calls and runs the applet
StartApplet.class (note that when the StartApplet.java is compiled the output is StartApplet.class.)
Writing HTML code for the program StartApplet Once the program has been written and
compiled, it has to be executed. The HTML document that calls and executes the applet is written
as follows:
<html>
<head>
<title>StartApplet</title>
</head>
<body bgcolor =“aaaaaa”>
<h!I> An Applet Program </hI>
<applet code=StartApplet.class width=40 height=40></applet>
</body>
</html>

The above HTML file is saved as AppletHtml.html. When this file is opened through a web
browser (either Internet Explorer or Netscape Navigator), the program StartApplet.class is
executed.
Invoking the applet without a HTML code Another method to invoke the applet without
writing the HTML code is by including the following code (code given in bold) in the StartApplet
program itself.

be Program 2.4 Executing an applet program without a HTML code.

import java.applet.*;
/*<applet code = StartApplet height = 400 width = 400></applet>*/
public class StartApplet extends Applet
{
String message = “Applet program.”;
String message1 =";
~ 28 Object Oriented Programming through Java

public void Start()


{
System.out.printin(message);
System.out.printIn(message
1);
}
public void init()
{
StartApplet Text;
Text = new StartApplet();
Text. message1 =“‘Writing the message.”;
Text.Start();

To run this program use appletviewer:


C:\> appletviewer StartApplet.java
Running the applet gives the following output:

Applet program.
Writing the message.

€ 2.5 Java Development Kit


Sun Microsystems offer the JDK, which is required to write, compile and run Java programs. This
is freely available on the web site of Sun Microsystems. In addition, JDK is offered as part of
commercial development environments by third-party vendors.
The JDK consists of the following:
Java development tools, including the compiler, debugger and the Java interpreter.
Java class libraries, organized into a collection of packages.
A number of sample programs.
Various supporting tools and components, including the source code of the classes in the
libraries.
Documentation describing all the packages, classes and methods in Java.
As already mentioned in the previous section, to transform a program into a format that
a computer can understand, a compiler is needed. The default Java compiler provided by the
JDK is called javac. In order to execute or run a program a run-time environment containing
a Java interpreter is needed. The Java interpreter provided by JDK is called java. Other run-
time environments include Java Run-time Environment (JRE), browsers with inbuilt runtime
environments and AppletViewer to execute/run applets even without a browser. The JDK also
Introduction to Java Programming 29°

provides a debugger tool for debugging programs. Debugging is the process of locating and
fixing errors in programs.

q 2.6 More Complex Programs


Look at Program 2.5. It introduces the concepts of access specifier, constructor and the keyword
Static.

I Program 2.5 A Java program with two classes.

class StartProgram Class declaration


{
public void Message()
{
System.out.printin (“This is a simple java program.”);
}
)
public class SecondProgram
{

|
public static void main(String args[])

StartProgram s= new StartProgram();


s.Message();
System.out.printin(“Two classes in a single java file”);
}

In Java, the class that contains the main method is the first one to be invoked by the JVM.
On compiling the file, the following two class files are created.
StartProgram.class
SecondProgram.class

On executing these class files, the output generated is


This is a simple java program.
Two classes in a single java file

2.6.1 Special features of this program

Access Specifier Access specifiers define the scope of a variable, method or class. Java provides
four access specifiers for attributes and methods, namely private, protected, public and default.
"30 Object Oriented Programming through Java

‘package private’ is a default specifier, which means there is no explicit specification given for an
attribute or a method. Access specifiers will be covered in chapter 4.
Constructors A constructor is a function that is automatically executed whenever an object is
created. It is used for initializing any class member. Constructors are dealt with in chapter 4.
Static The static keyword allocates memory. Until a method is static it will not be loaded into’
memory. ‘
The method main() Every Java file must contain a main() method (except applets, and servlets).
Each Java file may have more than one class and atleast one of these classes must have main. Java
executes the file specified at the command line in which the class containing the main method
exists. The signature of the main method is as follows:
public static void main(String args[])
The main() method always has public accessibility so that the interpreter can call it. It is a
static method belonging to the class. It does not return a value, that is, it is declared void. It always
has an array of String objects as its only formal parameter. This array contains any arguments
passed to the program on the command line.

& 2.7 Java Source File Structure

The source code of a Java program is written in a plain text file, which is commonly referred to as
Java source file. The extension of this file name is .java. The source file contains the code required
to perform a particular task.
A Java source file consists of the following elements:

¢ An optional package definition to bpecify a package name: classes and interfaces defined
in the file will belong to this package. If the package name is not given, the definitions will
belong to the default package.
¢ A number of class and interface definitions: technically a source file need not have any
such definitions, but that is hardly useful. The classes and interfaces can be defined in any
order. Note that JDK imposes the restriction that only one public class may be defined per
source file, and it requires that the file name match this public class. If the name of the
public class is NewApp then the file name must be NewApp.java.
The above structure is depicted by a skeletal source file as shown below.
Java Source File Structure

// Filename: NewApp.java
// PART 1: (OPTIONAL)
// Package name
package com.company.project.Package;
// PART 2: (ZERO OR MORE)
Introduction to Java Programming 34

// Packages used
import java.util.*;
import java.io.*;
// PART 3: (ZERO OR MORE)
/! Definitions of classes and interfaces (in any order)
public class NewApp {}
class C1 {}
interface I1 {}
th
class Cn {}
interface Im {}
// end of file

g 2.8 Prerequisites for Compiling and Running Java Programs


To write, compile and execute a java program, the first requirement is a Java development kit.
The Java 2 Standard Edition (J2SE) is a premier solution for rapidly developing and deploying
mission-critical, enterprise applications. It provides the essential compiler, tools, run-times
and APIs for writing, deploying and running applets and applications in the Java programming
language.
The J2SE is at the core of Java technology, and version 1.4 raises the Java platform to a higher
standard. From client to server, from desktop to supercomputer, improvements have been made
to J2SE across the board. With version 1.4, enterprises can now use Java technology to develop
more demanding business applications with less effort and in less time.
J2SE is available on the website of Sun Microsystems. This software development kit is freely
downloadable from the following website.
http://java.sun.com/j2se/1.4.1/download.html
The following link would give access to documentation.
http://java.sun.com/j2se/1.4/docs/index.htm!

In order to compile Java programs, the Standard Java Development Kit (J2SDK) has to be
downloaded and should be installed on the computer. After the software is installed, the class path
has to be set. The class path specifies where the Java library is available. In the Java library, two
Java files dt.jar and tools.jar are available.
Java became a popular object-oriented programming language because of its various features
and the complete Java software is freely available to work. In this chapter, we have covered the
history and characteristics of Java language. This chapter forms an introduction towards compiling
and executing Java program. From here we move on to the fundamentals of Java in chapter 3.

LAAT SELLE ELIE LLEST TE ELE SLE ETDS ESL TELETETE SI ELLIE EEL CAEL EE LETC EEL
Another Random Document on
Scribd Without Any Related Topics
¡Solo!

(PALACIO VALDÉS)

¡SOLO!
Fresnedo dormía profundamente su siesta acostumbrada. Al lado del
diván estaba el velador maqueado, manchado de ceniza de cigarro, y sobre
él un platillo y una taza, pregonando que el café no desvela a todas las
personas. La estancia, amueblada para el verano con mecedoras y sillas de
rejilla, estera fina de paja, y las paredes desnudas y pintadas al fresco, se
hallaba menos que a media luz: las persianas la dejaban a duras penas
filtrarse. Por esto no se sentía el calor. Por esto y porque nos hallamos en
una de las provincias más frescas del Norte de España y en el campo.
Reinaba silencio. Escuchábase sólo fuera el suave ronquido de las cigarras
y el pío pío de algún pájaro que, protegido por los pámpanos de la parra que
ciñe el balcón, se complacía en interrumpir la siesta de sus compañeros.
Alguna vez, muy lejos, se oía el chirrido de un carro, lento, monótono,
convidando al sueño. Dentro de la casa habían cesado ya tiempo hacía los
ruidos del fregado de los platos. La fregatriz, la robusta, la colosal Mariona,
como andaba descalza, sólo producía un leve gemido de las tablas, que se
quejaban al recibir tan enorme y maciza humanidad.
Cualquiera envidiaría aquella estancia fresca, aquel silencio dulce, aquel
sueño plácido. Fresnedo era un sibarita; pero solamente en el verano.
Durante el invierno trabajaba como un negro allá en su escritorio de la calle
de Espoz y Mina, donde tenía un gran establecimiento de alfombras. Era
hombre que pasaba un poco de los cuarenta, fuerte y sano como suelen ser
los que no han llevado una juventud borrascosa: la tez morena, el pelo
crespo, el bigote largo y comenzando a ponerse gris. Había nacido en
Campizos, punto donde nos hallamos, hijo de labradores regularmente
acomodados. Mandáronle a Madrid a los catorce años con un tío
comerciante. Trabajó con brío e inteligencia; fué su primer dependiente;
después, su asociado; por último se casó con su hija, y heredó su hacienda y
su comercio. Contrajo matrimonio tarde, cuando ya se acercaba a los
cuarenta años. Su mujer sólo tenía veinte. Educada en el bienestar y hasta
en el lujo que le podía procurar el viejo Fresnedo, Margarita era una de esas
niñas madrileñas, toda melindres, toda vanidad, postrada ante las mil
ridiculeces de la vida cortesana, cual si estuviesen determinadas por
sentencias de un código inmortal, desviada enteramente de la vida de la
Naturaleza y la verdad. Por eso odiaba el campo, y muy particularmente el
ignorado y frondoso lugarcito donde tenía origen su linaje humilde. Lo
odiaba casi tanto como su mamá, la esposa del viejo Fresnedo, que, a pesar
de ser hija de una cacharrera de la calle de la Aduana, tenía a menos poner
los pies en Campizos.
Tanto como ellas lo odiaban amábalo el buen Fresnedo. Mientras fué
dependiente de su tío, arrancábale todos los años licencia para pasar el mes
de Julio o Agosto en su país. Cuando sus ganancias se lo permitieron,
levantó al lado de la de sus padres una casita muy linda, rodeada de jardín,
y comenzó a comprar todos los pedazos de tierra que cerca de ella salían a
la venta. En pocos años logró hacerse un propietario respetable. Y al
compás que se hacía dueño de la tierra donde corrieron sus primeros años,
su amor hacia ella crecía desmesuradamente. Puede cualquiera figurarse el
disgusto que el honrado comerciante experimentó cuando, después de
casado con su prima, ésta le anunció, al llegar el verano, que no estaba
dispuesta «a sepultarse en Campizos», decisión que su tía y suegra reciente
apoyó con maravilloso coraje. Fué necesario resignarse a veranear en San
Sebastián. Al año siguiente, lo mismo. Pero al llegar al cuarto, Fresnedo
tuvo la audacia de rebelarse, produciendo un gran tumulto doméstico.—«O
a Campizos, o a ninguna parte este verano. ¿Estamos, señoras?» Y los
bigotes se le erizaron de tal modo inflexible al pronunciar estas enérgicas
palabras, que la delicada esposa se desmayó acto continuo, y la animosa
suegra, rociando las sienes de su hija con agua fresca y dándole a oler el
frasco del antiespasmódico, comenzó a increparle amargamente:
—¡Huele, hija mía, huele!... ¡Si las cosas se hicieran dos veces!... La
culpa la he tenido yo en poner en manos de un paleto una flor tan delicada.
Cuando la flor delicada abrió al fin los ojos, fué para soltar por ellos un
caudal de lágrimas y para decir con acento tristísimo:
—¡Nunca lo creyera de Ramón!
Fresnedo se conmovió. Hubo explicaciones. Al fin se transigió de un
modo honroso para las dos partes. Convínose en que Margarita y su mamá
irían a San Sebastián, llevando a la niña de quince meses, y que Fresnedo
fuése a Campizos el mes de Agosto, con Jesús, el niño mayor, de edad de
tres años, y su niñera. Esta es la razón de que Fresnedo se encuentre
durmiendo la siesta donde acabamos de verle.
Despertóle de ella una voz bien conocida:
—Papá, papá.
Abrió los ojos y vió a su hijo a dos pasos, con su mandilito de dril color
perla, sus zapatitos blancos y el negro y enmarañado cabello caído en
bucles graciosos sobre la frente. Era un chico más robusto que hermoso. La
tez, de suyo morena, teníala ahora requemada por los días que llevaba de
aldea haciendo una vida libre y casi salvaje. Su padre le tenía todo el día a
la intemperie, siguiendo escrupulosamente las instrucciones de su médico.
—Papá..., dijo Tata que tú no querías... que tú no querías... que tú no
querías... comprarme un carro... y que el carnero... y que el carnero no era
mío..., que era de Carmita (la hermana), y no me deja cogerlo por los
cuernos, y me pegó en la mano.
El chiquitín, al pronunciar este discurso con su graciosa media lengua,
deteniéndose a cada momento, mostraba en sus ojos negros y profundos la
indignación vivísima y mucha sed de justicia. Por un instante pareció que
iba a romper en llanto; pero su temperamento enérgico se sobrepuso, y
después de hacer una pausa cerró su perorata con una interjección de
carretero. El padre le había estado escuchando embelesado, animándole con
sus gestos a proseguir, lo mismo que si una música celeste le regalase los
oídos. Al oir la interjección, estalló en una sonora y alegre carcajada. El
niño le miró con asombro, no pudiendo comprender que lo que a él le ponía
tan fuera de sí causase el regocijo de su papá. Este hubiera estado
escuchándole horas y horas sin pestañear. Y eso que, según contaba su
suegra a las visitas, cuando quería dar el golpe de gracia a su yerno y
perderle completamente ante la conciencia pública, ¡¡¡se había dormido
oyendo La Favorita a Gayarre!!!
—¿Sí, vida mía? ¿La Tata no quiere que cojas el carnero por los
cuernos? ¡Deja que me levante, ya verás cómo arreglo yo a la Tata!
Fresnedo atrajo a su hijo y le aplicó dos formidables besos en las
mejillas, acariciándole al mismo tiempo la cabecita con las manos.
El chico no había agotado el capítulo de los agravios que creía haber
recibido de su niñera... Siguió gorjeando que ésta no había querido darle
pan.
—Hace poco tiempo que hemos comido.
—Hace mucho—dijo el niño con despecho.
—Bueno, ya te lo daré yo.
Además, la Tata no había querido contarle un cuento, ni hacer vaquitas
de papel. Además, le había pinchado con un alfiler aquí. Y señalaba una
manecita.
—¡Pues es cierto!—exclamó Fresnedo viendo, en efecto un ligero
rasguño.—¡Dolores! ¡Dolores!—gritó después.
Presentóse la niñera. El amo la increpó duramente por llevar alfileres en
la ropa, contra su prohibición expresa. Jesús, viendo a la Tata triste y
acobardada, fué a restregarse con sus faldas, como pidiéndole perdón de
haber sido causa de su disgusto.
—Bueno—dijo Fresnedo levantándose del diván y esperezándose.—
Ahora nos iremos al establo y cogerás al carnero por los cuernos. ¿Quieres,
Chucho?
Chucho quiso descoyuntarse la cabeza haciendo señales de afirmación
que corroboraba vivamente con su media lengua. Pero echando al mismo
tiempo una mirada tímida a su Tata, y viéndola todavía seria y avergonzada,
le dijo con encantadora sonrisa:
—No te enfades, boba; tú vienes también con nosotros.
Fresnedo se vistió su americana de dril, se cubrió con un sombrero de
paja, y tomando de la mano a su niño, bajó al jardín, y de allí se trasladaron
al establo. Al abrir la puerta, Chucho, que iba muy decidido, se detuvo y
esperó a que su padre penetrase. Estaba obscuro. Del fondo de la cuadra
salía el vaho tibio y húmedo que despide siempre el ganado. Las vacas
mugieron débilmente, lo cual puso en gran sobresalto a Jesús, que se negó
rotundamente a entrar, bajo el pretexto especioso de que se iba a manchar
los zapatos. Su padre le tomó entonces en brazos y pasó y quiso acercarle a
las vacas y que les pusiese la mano en el testuz. Chucho, que no las llevaba
todas consigo, confesó que a las vacas les tenía un «potito de miedo». A los
carneros ya era otra cosa. A éstos declaraba que no les temía poco ni
mucho; que jamás había sentido por ellos más que amor y veneración.
—Bueno, vamos a ver los carneros—dijo Fresnedo sonriendo.
Y se trasladaron al departamento de las ovejas. Allí pretendió dejarlo en
el suelo; mas en cuanto puso los piececitos en él, Jesús manifestó que
estaba cansadísimo, y hubo que auparlo de nuevo. Acercóle su padre a un
carnero y le invitó a que le tomase por un cuerno. Era cosa grave y digna de
meditarse. Chucho lo pensó con detenimiento. Avanzó un poco la mano, la
retiró otra vez, volvió a avanzarla, volvió a retirarla. Por último, se decidió
a manifestar a su papá que a los carneros les tenía «un potito miedo». Pero,
en cambio, dijo que a las gallinas las trataba con la mayor confianza; que en
su vida le habían inspirado el más mínimo recelo; que se sentía con fuerzas
para cogerlas del rabo, de las patas y hasta del pico, porque eran unos
animales cobardes y despreciables, al menos en su concepto. Fresnedo no
tuvo inconveniente en llevarle al gallinero, que estaba en la parte trasera de
la casa, fabricado con una valla de tela metálica. Allí Chucho, con una
bravura de que hay pocos ejemplos en la historia, se dirigió al gallo mayor,
enorme animal de casta española, soberbio de posturas y ardiente de ojo.
Trató de cogerle por el rabo, como había formalmente prometido, pero el
grave sultán del gallinero chilló de tal horrísona manera, extendiendo las
alas y dando feroces sacudidas, que el frío de la muerte penetró en el
corazón de Chucho. Apresuróse a soltarlo y se agarró aterrado al cuello de
su padre.
—Pero, hombre, ¿no decías que no tenías miedo a las gallinas?—
exclamó éste riendo.
—Tú, tú...; cógelo tú, papá.
—Yo tengo miedo.
—No, tú no tienes miedo.
—Y tú, ¿lo tienes?
Calló avergonzado; pero al fin confesó que a las gallinas también les
tenía «un potito de miedo».
Desde allí llevóle otra vez Fresnedo al establo, y después de varios
sustos y vacilaciones logró que pusiera su manecita en el hocico de un
becerro. Mas ocurriéndole al animal sacar la lengua y pasársela por la
mano, la aspereza de ella le produjo tal impresión, que no quiso ya
arrimarse a ningún otro individuo de la raza vacuna. Subióle después al
pajar. ¡Qué placer para Chucho! ¡Hundirse en la crujiente hierba, agarrarla y
esparcirla en pequeños puñados; dejarse caer hacia atrás con los brazos
abiertos! Pero aún era mayor el gozo de su padre contemplándole. Jugaron a
sepultarse vivos. Fresnedo se dejaba enterrar por su hijo, que iba
amontonando hierba sobre él con vigor y crueldad que nadie esperara de él.
Mas a lo mejor de la operación, su papá daba una violenta sacudida y
echaba a volar toda la hierba. Y con esto el chico soltaba nuevas carcajadas,
como si aquello fuese el caso más chistoso de la tierra. Sudaba una gota por
todos los poros de su tierno cuerpecito, tenía los cabellos pegados a la
frente y el rostro encendido. Cuando su papá trató de tomar la revancha y
sepultarle a él, no pudo resistirlo. Así que se halló con hierba sobre los ojos,
dióse a gritar y concluyó por llorar con verdadero sentimiento, cayéndole
por las mejillas unas lágrimas que su padre se apresuró a beber con besos
apasionados.
Sí; en aquel momento a Fresnedo le atacó uno de esos accesos de ternura
que solían ser en él frecuentes. Jesús era su familia, todo su amor, la única
ilusión de su vida. Si entrásemos por los últimos pliegues de su corazón, es
posible que no halláramos ya un átomo de cariño hacia su mujer. El carácter
altanero, impertinente y desabrido de ésta había matado el fuego de la
pasión que sintió por ella al casarse. Pero aquel tierno pimpollo, aquel
botón de rosa, aquel pastelito dulce amasado por los ángeles lo llenaba
todo, ocupaba enteramente su vida, era el fondo de sus pensamientos, el
consuelo de sus pesares. Abrazábalo con arrebato y cubría sus frescas
mejillas con besos prolongados apretadísimos, murmurando después a su
oído palabras fogosas de enamorado.
—¿Quién te quiere más que nadie en el mundo, hermoso mío? ¿No es tu
papá? Di, lucero. Y tú, ¿a quién quieres más? Sí, vida mía, sí; te quiero
tanto, que daría por ti la vida con gusto. Por ti, nada más que por ti, quisiera
ser algo de provecho en el mundo. Por ti, sólo por ti, trabajo y trabajaré
hasta morir! ¡Nunca te podré pagar lo feliz que me haces, criatura!
El niño no comprendía, pero adivinaba aquella pasión y la correspondía,
finamente. Sus grandes ojos negros, expresivos, se posaban en su padre,
esforzándose por penetrar en aquel mundo de amor y descifrar el sentido de
palabras tan fervorosas. Después de un momento de silencio en que pareció
que meditaba, tomó con sus manecitas como claveles la cara de su padre, y
acercando la boca a su oído, le dijo con voz tenue como un soplo:
—Papá, voy a decirte una cosa... Te quiero más que a mamá... No se lo
digas, ¿eh?
Al buen Fresnedo se le humedecían los ojos con estas cosas.
Bajaron del pajar, salieron del establo, y después de consultado el reloj,
el comerciante resolvió irse a bañar, como todos los días, al río.
—Chucho, ¿vienes conmigo al baño?
¡Cielo santo, qué felicidad!
Chucho quiso volverse loco de alegría. Generalmente el baño de su
padre le causaba algunas lágrimas porque no podía llevarle consigo a causa
de la niñera. Fresnedo se bañaba en un sitio retirado, pero en cueros vivos.
Esta vez se decidió a llevar a su hijo y dejar a Dolores en casa. El niño
comenzó a pedir a grandes gritos el sombrero. No quería subir por él a casa,
temiendo que su padre se le escapase como otras veces. La Tata, riendo, se
lo tiró del balcón, y lo mismo la sábana del papá y la sombrilla.
El río estaba a un kilómetro de la casa. Era necesario caminar por unas
callejas bordadas de toscas paredillas recamadas de zarzamora y
madreselva. El sol empezaba a declinar, y el valle, el hermoso valle de
Campizos, rodeado de suaves colinas pobladas de castañares, y en segundo
término de un cinturón de elevadísimas montañas, cuyas crestas nadaban en
un vapor violáceo, dormía la siesta silencioso, ostentando su manto de
verdura incomparable. Había todos los matices del verde en este manto,
desde el claro amarillento de la hierba tierna, hasta el obscuro y profundo
de los robles y negrillos.
Caminaban padre e hijo por las angostas calles preservándose del sol con
la sombrilla del primero. Pero Chucho se escapaba muchas veces y
Fresnedo le dejaba libre, convencido de que era bueno acostumbrarlo a
todo. Gozaba al verle correr delante, con su mandilito de dril y su gran
sombrero de paja con cintas azules. Chucho andaba cuatro veces el camino,
como los perros. Paraba a cada instante para coger las florecitas que estaban
al alcance de su mano, y las que no, obligaba despóticamente a su padre a
cogerlas y además a cortar algunas ramas de los árboles, con las cuales iba
barriendo el camino. Por cierto que en medio de él tuvo un encuentro
desdichado y temeroso. Al doblar un recodo tropezóse nuestro niño con un
cerdo, un gran cerdo negro y redondo, caminando en la misma dirección.
Chucho tuvo la temeridad de acercarse a él y cogerle por el rabo. Este
aditamento de los animales ejercía una influencia magnética sobre sus
diminutas manos regordetas. El cerdo que estaba, al parecer, de mal humor
y nervioso, al sentirse asido lanzó un terrible bufido, y dando la vuelta para
escapar, embistió con el niño y lo volcó. ¡Cristo Padre, qué grito! Allá
acudió Fresnedo corriendo, y lo levantó y le limpió las lágrimas y el polvo,
haciéndole presente al mismo tiempo que tomaría venganza de aquel cerdo
bárbaro y descortés así que llegaran a casa. Con lo cual se aplacó Chucho,
no sin manifestar antes que el cerdo era muy feo y que a él le gustaban más
los perros, porque eran buenos y le conocían, y cuando estaban de humor le
lamían la cara.
Hubo que pasar por algunas saltaderas. Fresnedo tomaba a su hijo en
brazos y le ponía de la parte de allá con gran cuidado. Dejaron el camino
real y empezaron a caminar por los prados, donde Jesús se empeñó en coger
un grillo. Su padre le mandó orinar en el agujero para que saliese. Así lo
hizo, y como el grillo no quería asomar, se irritó contra sí mismo porque no
podía orinar más y lloró desconsoladamente. Aunque con gran sentimiento,
renunció a aquella caza difícil y se dedicó a las anitas de Dios, y se
entretuvo un rato, demasiado largo, en opinión de su papá, a ponerlas en la
palma de la mano, cantándoles: Anita, anita de Dios, abra las alas y vete
con Dios, precioso conjuro que la había enseñado su Tata, persona muy
instruída en este linaje de conocimientos.
Por fin llegaron al río. Corría sereno y límpido por entre praderas, orlado
de avellanos que salen de la tierra como grandes ramilletes. Formaba en
aquel paraje un remanso que llamaban en la aldea el Pozo de Tresagua. Era
el pozo bastante hondo, el sitio retirado y deleitoso. Ningún otro había en
los contornos de Campizos más a propósito para bañarse. Llegaba el césped
hasta la misma orilla, y sobre aquella verde alfombra era grato sentarse y
cómodamente se podía cualquiera desnudar sin peligro de ser visto. Los
avellanos, macizos de verdura, no dejaban pasar los rayos del sol, que aún
lucía vivo y ardiente. Allí gozaba Fresnedo del baño más que el sultán de
Turquía, acumulando salud y felicidad para todo el año. En aquel mismo
sitio se había bañado de niño con otra porción de compañeros que hoy eran
labradores. ¡Qué placer sentía recordando los pormenores de su vida
infantil, cuando era un zagalillo a quien su padres recomendaban el cuidado
del ganado en el monte o les ayudaba en todas las faenas de la agricultura!
Cuando los recuerdos de la infancia van unidos a una vida libre en el seno
de la Naturaleza, por pobre que se haya sido, siempre aparecen alegres,
deliciosos.
Descansaron algunos minutos padre e hijo sobre el césped «reposando el
calor», y al fin se decidió aquel a ir despojándose poco a poco de la ropa.
Mientras lo hacía, tarareaba una canción de zarzuela de las que llegaban a
sus oídos de Madrid. La alegría le rebosaba del alma. Su hijo le miraba
atentamente con sus grandes ojos negros. De vez en cuando Fresnedo
levantaba los suyos hacia él, y le decía sonriendo:
—¿Qué hay, Chucho? ¿Te quieres bañar conmigo?
Chucho se contentaba con reir, como diciendo:
¡Qué bromista es este papá! ¡Como si no supiese que armo un escándalo
cada vez que intentan meterme en el agua!
Fresnedo se bañaba enteramente desnudo. Le incomodaba mucho
cualquier traje de baño. En aquel sitio tenía la seguridad de no ser visto.
Cuando se quedó en cueros vivos, el asombro y la curiosidad retratados en
la cara de su «Chipilín», le causaron cierta vergüenza y se cubrió con la
sábana. Pero Chucho no estaba conforme y empezó a gorjear, mientras
tiraba de la sábana con sus manecitas, «que su papá tenía pelo en el cuerpo
y que él no lo tenía, y que la Tata tampoco lo tenía...»
—Vamos, Chucho, cállate—le dijo el papá con semblante grave—. No
se habla de eso. Los niños no hablan de eso.
—¿Y por qué no hablan los niños de eso? Fresnedo no contestó.
—¿Por qué no hablan los niños de eso, papá?—repitió el chico.
El comerciante quiso distraerle hablándole de otras cosas, pero Chucho
no acudió al engaño.
—¿Por qué no hablan los niños de eso, papá?—insistió lleno de
curiosidad.
—Porque no está bien—respondió.
—¿Y por qué no está bien?
—¡Vaya, vaya, déjame en paz!—exclamó entre impaciente y risueño.
Embozado en la sábana como en un jaique moruno avanzó hacia el agua.
—Mira, Chucho—dijo volviéndose—, no te muevas de ahí. Sentadito
hasta que yo salga, ¿verdad?... Mira, vas a ver cómo me tiro de cabeza al
agua. Mira bien. A la una..., a las dos... Mira bien, Chucho... ¡A las tres!
Fresnedo, que había dejado caer la sábana al dar las voces y se había
colocado sobre un pequeño cantil, lanzóse, en efecto de cabeza al pozo con
el placer que lo hacen los hombres llenos de vida. Al hundirse, su cuerpo
robusto agitó violentamente el agua, produjo en ella una verdadera
tempestad, cuyas gotas salpicaron al mismo Jesús. Este sufrió un
estremecimiento y quedó atónito, maravillado, al ver prontamente salir a su
padre y nadar haciendo volteretas y cabriolas en el agua.
—¡Mira, Chucho! ¡Mira!
Y se puso con el vientre arriba, dejándose flotar sin movimiento alguno.
—Mira, mira ahora.
Y nadaba hacia atrás con los pies solamente.
—Verás ahora: voy a nadar como los perros.
Nadaba, en efecto, chapoteando el agua con las palmas de las manos.
¡Con qué gozo recordaba el rico comerciante aquellas habilidades
aprendidas en la niñez!
Chucho estaba arrobado en éxtasis delicioso contemplándole. No perdía
uno solo de sus movimientos.
—¡Chucho! ¡Chuchín! ¡Bien mío! ¿Quién te quiere?—gritaba Fresnedo
embriagado por la felicidad que las caricias del agua y los ojos inocentes de
su hijo le producían.
El niño guardaba silencio completamente absorto y atento a los juegos
natatorios de su padre.
—Vamos, di, Chipilín, ¿quién te quiere?
—Papá—respondió grave con su voz levemente ronca, sin dejar de
contemplarle atentamente.
Una de las habilidades en que Fresnedo había sobresalido de niño y que
mucho le enorgullecía, era la de pescar truchas a mano. Siempre que venía a
Campizos se ejercitaba en esta pesca. Era verdaderamente notable su
destreza para reconocer y batir los agujeros de las rocas, bloquear la trucha
y agarrarla por las agallas al fin. Los pescadores del país confesaban que se
las podía haber con cualquiera de ellos, y se contaba que de niño había
salido del agua con tres truchas, una en cada mano y otra en la boca, aunque
Fresnedo no quería confirmarlo. Pues bien; en este momento le acometió el
deseo de proporcionar un placer a su hijo y dárselo a sí mismo.
—Verás, Chipilín, voy a sacarte una trucha... ¿Quieres?
¡Ya lo creo que quería!
¡Pues si cabalmente Chucho sentía mayor inclinación, si cabe, a los
animales acuáticos que a los terrestres!
Fresnedo hizo una larga aspiración y se sumergió, dejando a su hijo
maravillado; registró los huecos de algunas piedras del fondo, y sólo pudo
tocar con los dedos la cola de una trucha sin lograr agarrarla. Como le
faltase el aliento, subió a respirar.
—Chucho, no he podido cogerla; pero ya caerá.
—¿Por qué caerá, papá?—preguntó el niño que no dejaba escapar un
modismo sin hacer que se lo explicasen.
—Quiero decir que ya la cogeré.
Otra vez aspiró el aire con fuerza y se lanzó al fondo. Al cabo de unos
momentos salió a la superficie con una trucha en la mano, que arrojó a la
orilla. Chucho dió un grito de susto y alegría al ver a sus pies al animalito
brincando y retorciéndose con furia. Quería agarrarlo cuando paraba un
instante; pero al acercar su manecita la trucha daba un salto, y el chico,
estremecido, la retiraba vivamente; intentaba nuevamente asirla lanzando
chillidos alegres, y otro salto le asustaba y le ponía súbito grave. Estaba
nervioso; gritaba, reía, hablaba, lloraba a un tiempo mismo, mientras su
padre, embelesado, nadaba suavemente contemplándole.
—¡Anda, valiente! ¡Agárrala, que no te hace nada!... ¡Por la cola,
tonto!... ¿Quieres que te pesque otra más grande?
—Sí, más gande, papá. Esta no me gusta—respondió el chiquito
renunciando ya bravamente a agarrar una trucha tan pequeña.
El buen comerciante se preparó para otro chapuz; dejóse ir al fondo y
con prisa comenzó a registrar los agujeros de una roca grande que antes
había visto. La muerte feroz y traidora aguardaba dentro. Metió el brazo en
uno de ellos harto angosto, y cuando intentó sacarlo no pudo. La sangre se
le agolpó toda al corazón. Perdió la serenidad para buscar la postura en que
había entrado. Forcejeó en vano algunos momentos. Abrió la boca al fin,
falto de aliento, y en pocos segundos quedó asfixiado el infeliz.
Chucho esperó en vano su salida. Miró con gran curiosidad por algunos
minutos el agua, hasta que, cansado de esperar, dijo con inocente
naturalidad:
—¡Papá, sal!
El padre no obedeció. Esperó unos instantes, y volvió a gritar con más
energía:
—¡Papá, sal!
Y cada vez más impaciente, repitió este grito, concluyendo por llorar.
Largo rato estuvo diciendo lo mismo con desesperación:
—¡Sal, papá, sal!
Sus rosadas mejillas estaban bañadas de lágrimas; sus ojos grandes,
hermosos, inocentes, se fijaban ansiosos en el pozo donde a cada instante se
figuraba ver salir a su padre.
Un salto de la trucha que tenía cerca, viva aún, le distrajo. Acercó su
manecita a ella y la tocó con un dedo. La trucha se movió levemente. Volvió
a tocarla y se movió menos aún. Entonces, alentado por el abatimiento del
animal, se atrevió a posar la palma de la mano sobre él. La trucha no
rebulló. Chucho principió a gorjear por lo bajo que él no tenía miedo a las
truchas y que si estuviera allí su hermana Carmita indudablemente no osaría
poner la mano sobre una bestia tan feroz como aquélla. Tanto se fué
envalentonando, que concluyó por agarrarla por la cola y suspenderla.
Aquel acto de heroísmo despertó en él mucha alegría. Fluyeron de su
garganta algunas sonoras carcajadas. Pero una violenta sacudida de la
trucha le obligó a soltarla aterrado. Miró a su alrededor, y no viendo a
nadie, se fijó otra vez en el pozo y tornó a gritar, llorando:
—¡Sal, papá! ¡Sal, papá!... ¡No quero trucha, papá! ¡Sal!
El sol declinaba. Aquel retirado paraje, situado en la falda misma de la
colina, se iba poblando de sombras. Allá, en el horizonte, el sol se ocultaba
detrás de las altas y lejanas montañas de color violeta.
—Teno miedo, papá... ¡Sal, papaíto!—gritaba la tierna criatura bebiendo
lágrimas.
Ninguna voz respondía a la suya. Escuchábanse tan sólo las esquilas del
ganado o algún mujido lejano. El río seguía murmurando suavemente su
eterna queja.
Rendido, ronco de tanto gritar, Chucho se dejó caer sobre el césped y se
durmió. Pero su sueño fué intranquilo. Era una criatura excesivamente
nerviosa, y la agitación con que se había dormido le hizo despertar al poco
rato. Había cerrado la noche. Al principio no se dió cuenta de dónde estaba,
y dijo como otras veces en su camita:
—Tata, quero agua.
Pero viendo que la Tata no acudía, se incorporó sobre el césped, miró
alrededor, y su pequeño corazón se encogió de terror observando la
obscuridad que reinaba.
—¡Tata, Tata!—gritó repetidas veces...
La luz de la luna rielaba en el agua. Atraídos sus ojos hacia ella, Chucho
se acordó de pronto que su papá estaba con él y se había metido en el río a
sacarle una trucha. Y entre sollozos que le rompían el pecho y lágrimas que
le cegaban, volvió a gritar:
—¡Sal, papá; sal, mi papá!... ¡Teno miedo!
La voz del niño resonaba tristemente en la obscura campiña silenciosa.
¡Ah! Si el buen Fresnedo pudiera escucharle allá en el fondo del pozo,
hubiera mordido la roca que le tenía sujeto, se hubiera arrancado el brazo
para acudir a su llamamiento.
No pudiendo ya gritar más porque le faltaba la voz y el aliento,
destrozado por el cansancio, cayó otra vez dormido, y así le hallaron los que
habían salido en su busca.
El Rey Burgués.

(RUBÉN DARÍO)

EL REY BURGUES
¡Amigo!, el cielo está opaco; el aire, frío; el día, triste. Un cuento
alegre..., así como para distraer las brumosas y grises melancolías, helo
aquí.
* * *
Había en una ciudad inmensa y brillante un rey muy poderoso, que tenía
trajes caprichosos y ricos, esclavas desnudas, blancas y negras; caballos de
largas crines, armas flamantísimas, galgos rápidos y monteros con cuernos
de bronce, que llenaban el viento con sus fanfarrias. ¿Era un rey poeta? No,
amigo mío: era el Rey Burgués.
* * *
Era muy aficionado a las artes el soberano y favorecía con gran largueza
a sus músicos, a sus hacedores de ditirambos, pintores, escultores,
boticarios, barberos y maestros de esgrima.
Cuando iba a la floresta, junto al corzo o jabalí herido y sangriento, hacía
improvisar a sus profesores de retórica canciones alusivas; los criados
llenaban las copas del vino de oro que hierve, y las mujeres batían palmas
con movimientos rítmicos y gallardos. Era un rey sol, en su Babilonia llena
de músicas, de carcajadas y de ruido de festín. Cuando se hastiaba de la
ciudad bullente, iba de caza, atronando el bosque con sus tropeles; y hacía
salir de sus nidos a las aves asustadas, y el vocerío repercutía en lo más
escondido de las cavernas. Los perros, de patas elásticas, iban rompiendo la
maleza en la carrera, y los cazadores, inclinados sobre el pescuezo de los
caballos, hacían ondear los mantos purpúreos, y llevaban las caras
encendidas y las cabelleras al viento.
* * *
El rey tenía un palacio soberbio, donde había acumulado riquezas y
objetos de arte maravilloso. Llegaba a él por entre grupos de lilas y
extensos estanques, siendo saludado por los cisnes de cuellos blancos antes
que por los lacayos estirados. Buen gusto. Subía por una escalera llena de
columnas de alabastro y de esmaragdina, que tenía a los lados leones de
mármol, como los de los troncos salomónicos. Refinamiento. A más de los
cisnes tenía una vasta pajarera, como amante de la armonía, del arrullo, del
trino; y cerca de ella iba a ensanchar su espíritu leyendo novelas de M.
Ohnet, o bellos libros sobre cuestiones gramaticales, o críticas
hermosillescas. Eso sí, defensor acérrimo de la corrección académica en
letras, y del modo lamido en artes; alma sublime amante de la lija y de la
ortografía.
* * *
¡Japonerías! ¡Chinerías!, por lujo, y nada más.
Bien podía darse el placer de un salón digno del gusto de un Goncourt y
de los millones de un Creso: quimeras de bronce con las fauces abiertas y
las colas enroscadas, en grupos fantásticos y maravillosos; lacas de Kioto
con incrustaciones de hojas y ramas de una flora monstruosa, y animales de
una fauna desconocida; mariposas de raros abanicos junto a las paredes;
peces y gallos de colores; máscaras de gestos infernales y con ojos como si
fuesen vivos; partesanas de hojas antiquísimas y empuñaduras con dragones
devorando flores de loto; y en conchas de huevo, túnicas de seda amarilla,
como tejidas con hilos de araña, sembradas de garzas rojas y de verdes
matas de arroz; y tibores, porcelanas de muchos siglos, de aquellas en que
hay guerreros tártaros con una piel que les cubre hasta los riñones, y que
llevan arcos estirados y manojos de flechas.
Por lo demás, había el salón griego, lleno de mármoles: diosas, musas,
ninfas y sátiros; el salón de los tiempos galantes con cuadros del gran
Watteau y de Chardin; dos, tres, cuatro, ¡cuántos salones!
Y Mecenas se paseaba por todos, con la cara inundada de cierta
majestad, el vientre feliz y la corona en la cabeza, como un rey de naipe.
* * *
Un día le llevaron una rara especie de hombre ante su trono, donde se
hallaba rodeado de cortesanos, de retóricos y de maestros de equitación y de
baile.
—¿Qué es eso?—preguntó.
—Señor, es un poeta.
El rey tenía cisnes en el estanque, canarios, gorriones, senzontes en la
pajarera: un poeta era algo nuevo y extraño.
—Dejadle aquí.
Y el poeta:
—Señor, no he comido.
Y el rey:
—Habla, y comerás.
Comenzó:
* * *
—Señor, ha tiempo que yo canto el verbo del porvenir. He tendido mis
alas al huracán, he nacido en el tiempo de la aurora: busco la raza escogida
que debe esperar, con el himno en la boca y la lira en la mano, la salida del
gran sol. He abandonado la inspiración de la ciudad malsana, la alcoba llena
de perfumes, la musa de carne que llena el alma de pequeñez y el rostro de
polvos de arroz. He roto el arpa adulona de las cuerdas débiles contra las
copas de Bohemia y las jarras donde espumea el vino que embriaga sin dar
fortaleza; he arrojado el manto que me hacía parecer histrión, o mujer, y he
vestido de modo salvaje y espléndido: mi harapo es de púrpura. He ido a la
selva, donde he quedado vigoroso y ahito de leche fecunda y licor de nueva
vida; y en la ribera del mar áspero, sacudiendo la cabeza bajo la fuerte y
negra tempestad, como un ángel soberbio, o como un semidiós olímpico, he
ensayado el yambo dando al olvido el madrigal.
He acariciado a la gran Naturaleza, y he buscado el calor del ideal, el
verso que está en el astro en el fondo del cielo, y el que está en la perla en
lo profundo del Océano. ¡He querido ser pujante! Porque viene el tiempo de
las grandes revoluciones, con un Mesías todo luz, todo agitación y potencia,
y es preciso recibir su espíritu con el poema que sea arco triunfal, de
estrofas de acero, de estrofas de oro, de estrofas de amor.
¡Señor!, el arte no está en los fríos envoltorios de mármol, ni en los
cuadros lamidos, ni en el excelente señor Ohnet! ¡Señor!, el arte no viste
pantalones, ni habla en burgués, ni pone los puntos en todas las íes. El es
augusto, tiene mantos de oro, o de llamas, o anda desnudo, y amasa la greda
con fiebre, y pinta con luz, y es opulento, y da golpes de ala como las
águilas, o zarpazos como los leones. Señor, entre un Apolo y un ganso,
preferid al Apolo, aunque el uno sea de tierra cocida y el otro de marfil.
¡Oh, la poesía!
¡Y bien! Los ritmos se prostituyen, se cantan los lunares de las mujeres y
se fabrican jarabes poéticos. Además, señor, el zapatero critica mis
endecasílabos, y el señor profesor de farmacia pone puntos y comas a mi
inspiración. Señor, ¡y vos lo autorizáis todo esto!... El ideal, el ideal...
El rey interrumpió:
—Ya habéis oído. ¿Qué hacer?
Y un filósofo al uso:
—Si lo permitís, señor, puede ganarse la comida con una caja de música;
podemos colocarle en el jardín, cerca de los cisnes, para cuando os paseéis.
—Sí—dijo el rey; y dirigiéndose al poeta:—Daréis vueltas a un
manubrio. Cerraréis la boca. Haréis sonar una caja de música que toca
valses, cuadrillas y galopas, como no prefiráis moriros de hambre. Pieza de
música por pedazo de pan. Nada de jerigonzas ni de ideales. Id.
Y desde aquel día pudo verse a la orilla del estanque de los cisnes al
poeta hambriento, que daba vueltas al manubrio: tiririrín, tiririrín...,
¡avergonzado a las miradas del gran sol! ¿Pasaba el rey por las cercanías?
¡Tiririrín, tiririrín...! ¿Había que llenar el estómago? ¡Tiririrín! Todo entre
las burlas de los pájaros libres que llegaban a beber rocío en las lilas
floridas, entre el zumbido de las abejas que le picaban el rostro y le llenaban
los ojos de lágrimas..., ¡lágrimas amargas que rodaban por sus mejillas y
que caían a la tierra negra!
Y llegó el invierno, y el pobre sintió frío en el cuerpo y en el alma. Y su
cerebro estaba como petrificado, y los grandes himnos estaban en el olvido,
y el poeta de la montaña coronada de águilas no era sino un pobre diablo
que daba vueltas al manubrio: ¡tiririrín!
Y cuando cayó la nieve se olvidaron de él el rey y sus vasallos; a los
pájaros se les abrigó, y a él se le dejó al aire glacial, que le mordía las
carnes y le azotaba el rostro.
Y una noche en que caía de lo alto la lluvia blanca de plumillas
cristalizadas, en el palacio había festín, y la luz de las arañas reía alegre
sobre los mármoles, sobre el oro y sobre las túnicas de los mandarines de
las viejas porcelanas. Y se aplaudían hasta la locura los brindis del señor
profesor de retórica, cuajados de dáctilos, de anapestos y de pirriquios,
mientras en las copas cristalinas hervía el Champaña con su burbujeo
luminoso y fugaz. ¡Noche de invierno, noche de fiesta! Y el infeliz, cubierto
de nieve, cerca del estanque, daba vueltas al manubrio para calentarse,
tembloroso y aterido, insultado por el cierzo, bajo la blancura implacable y
helada, en la noche sombría, haciendo resonar entre los árboles sin hojas la
música loca de las galopas y cuadrillas; y se quedó muerto, pensando en
que nacería el sol del día venidero, y con él el ideal..., y en que el arte no
vestiría pantalones, sino manto de llamas de oro... Hasta que al día siguiente
lo hallaron el rey y sus cortesanos, al pobre diablo de poeta, como gorrión
que mata el hielo, con una sonrisa amarga en los labios, y todavía con la
mano en el manubrio.
* * *
¡Oh, mi amigo!, el cielo está opaco; el aire frío; el día, triste. Flotan
brumosas y grises melancolías...
Pero, ¡cuánto calienta el alma una frase, un apretón de manos a tiempo!
Hasta la vista
!
Elizabide el Vagabundo.

(BAROJA)

ELIZABIDE EL VAGABUNDO
¿Cer zala usté cenuben
enamoratzia?
Sillau is hira eta
guitarra jotzia.

(CANTO POPULAR)

Muchas veces, mientras trabajaba en aquel abandonado jardín, Elizabide


el Vagabundo se decía al ver pasar a Maintoni, que volvía de la iglesia:
—¿Qué pensará?—¿Vivirá satisfecha? ¡La vida de Maintoni le parecía
tan extraña! Porque era natural que quien como él había andado siempre a
la buena de Dios rodando por el mundo, encontrara la calma y el silencio de
la aldea deliciosos; pero ella, que no había salido nunca de aquel rincón,
¿no sentiría deseos de asistir a teatros, a fiestas, a diversiones, de vivir otra
vida más espléndida, más intensa? Y como Elizabide el Vagabundo no se
daba respuesta a su pregunta, seguía removiendo la tierra con su azadón
filosóficamente.
—Es una mujer fuerte—pensaba después;—su alma es tan serena, tan
clara, que llega a preocupar. Una preocupación científica, sólo científica,
eso claro. Y Elizabide el Vagabundo, satisfecho de la seguridad que se
concedía a sí mismo de que íntimamente no tomaba parte en aquella
preocupación, seguía trabajando en el jardín abandonado de su casa.
Era un tipo curioso el de Elizabide el Vagabundo. Reunía todas las
cualidades y defectos del vascongado de la costa: era audaz, irónico,
perezoso, burlón. La ligereza y el olvido constituían la base de su
temperamento: no daba importancia a nada, se olvidaba de todo. Había
gastado casi entero su escaso capital en sus correrías por América, de
periodista en un pueblo, de negociante en otro, aquí vendiendo ganado, allá
comerciando en vinos. Estuvo muchas veces a punto de hacer fortuna, lo
que no consiguió por indiferencia. Era de esos hombres que se dejan llevar
por los acontecimientos sin protestar nunca. Su vida, él la comparaba con la
marcha de uno de esos troncos que van por el río, que si nadie los recoge se
pierden al fin en el mar.
Su inercia y su pereza eran más de pensamiento que de manos; su alma
huía de él muchas veces: le bastaba mirar al agua corriente, contemplar una
nube o una estrella para olvidar el proyecto más importante de su vida, y
cuando no lo olvidaba por esto, lo abandonaba por cualquier otra cosa, sin
saber por qué muchas veces.
Ultimamente se había encontrado en una estancia del Uruguay, y como
Elizabide era agradable en su trato y no muy desagradable en su aspecto,
aunque tenía ya sus treinta y ocho años, el dueño de la estancia le ofreció la
mano de su hija, una muchacha bastante fea que estaba en amores con un
mulato. Elizabide, a quien no le parecía mal la vida salvaje de la estancia,
aceptó, y ya estaba para casarse cuando sintió la nostalgia de su pueblo, del
olor a heno de sus montes, del paisaje brumoso de la tierra vascongada.
Como en sus planes no entraban las explicaciones bruscas, una mañana, al
amanecer, advirtió a los padres de su futura que iba a ir a Montevideo a
comprar el regalo de boda; montó a caballo, luego en el tren; llegó a la
capital, se embarcó en un transatlántico, y después de saludar
cariñosamente la tierra hospitalaria de América, se volvió a España.
Llegó a su pueblo, un pueblecillo de la provincia de Guipúzcoa; abrazó a
su hermano Ignacio, que estaba allí de boticario; fué a ver a su nodriza, a
quien prometió no hacer ninguna escapatoria más, y se instaló en su casa.
Cuando corrió por el pueblo la voz de que no sólo no había hecho dinero en
América, sino que lo había perdido, todo el mundo recordó que antes de
salir de la aldea ya tenía fama de fatuo, de insubstancial y de vagabundo.
El no se preocupaba absolutamente nada por estas cosas; cavaba en su
huerta, y en los ratos perdidos trabajaba en construir una canoa para andar
por el río, cosa que a todo el pueblo indignaba.
Elizabide el Vagabundo creía que su hermano Ignacio, la mujer y los
hijos de éste le desdeñaban, y por eso no iba a visitarles más que de cuando
en cuando; pero pronto vió que su hermano y su cuñada le estimaban y le
hacían reproches porque no iba a verlos. Elizabide comenzó a acudir a casa
de su hermano con más frecuencia.
La casa del boticario estaba a la salida del pueblo, completamente
aislada; por la parte que miraba al camino tenía un jardín rodeado de una
tapia, y por encima de ella salían ramas de laurel de un verde obscuro que
protegían algo la fachada del viento del Norte. Pasando el jardín estaba la
botica.
La casa no tenía balcones, sino sólo ventanas, y éstas abiertas en la pared
sin simetría alguna; quizás esto era debido a que algunas de ellas estaban
tapiadas.
Al pasar en el tren o en el coche de las provincias del Norte, ¿no habéis
visto casas solitarias que, sin saber por qué, os daban envidia? Parece que
allá dentro se debe vivir bien, se adivina una existencia dulce y apacible; las
ventanas con cortinas hablan de interiores casi monásticos, de grandes
habitaciones amuebladas con arcas y cómodas de nogal, de inmensas camas
de madera; de una existencia tranquila, sosegada, cuyas horas pasan lentas,
medidas por el viejo reloj de alta caja que lanza en la noche su sonoro tic-
tac.
La casa del boticario era de éstas: en el jardín se veían jacintos,
heliotropos, rosales y enormes hortensias que llegaban hasta la altura de los
balcones del piso bajo. Por encima de la tapia del jardín caían como en
cascada un torrente de rosas blancas, sencillas, que en vascuence se llaman
choruas (locas) por lo frívolas que son y por lo pronto que se marchitan y se
caen.
Cuando Elizabide el Vagabundo fué a casa de su hermano, ya con más
confianza, el boticario y su mujer, seguidos de todos los chicos, le
enseñaron la casa, limpia, clara y bien oliente; después fueron a ver la
huerta, y aquí Elizabide el Vagabundo vió por primera vez a Maintoni, que,
con la cabeza cubierta con un sombrero de paja, estaba recogiendo
guisantes en la falda del delantal. Elizabide y ella se saludaron fríamente.
—Vamos hacia el río—le dijo a su hermana la mujer del boticario.—
Diles a las chicas que lleven el chocolate allí.
Maintoni se fué hacia la casa, y los demás, por una especie de túnel largo
formado por perales que tenían las ramas extendidas como las varillas de un
abanico, bajaron a una plazoleta que estaba junto al río, entre árboles, en
donde había una mesa rústica y un banco de piedra. El sol, al penetrar entre
el follaje, iluminaba el fondo del río y se veían las piedras redondas del
cauce y los peces que pasaban lentamente brillando como si fueran de plata.
La tarde era de una tranquilidad admirable; el cielo azul, puro y tranquilo.
Antes del caer de la tarde las dos muchachas de casa del boticario
vinieron con bandejas en la mano trayendo chocolate y bizcochos. Los
chicos se abalanzaron sobre los bizcochos como fieras. Elizabide el
Vagabundo habló de sus viajes, contó algunas aventuras, y tuvo suspensos
de sus labios a todos. Sólo ella, Maintoni, pareció no entusiasmarse gran
cosa con aquellas narraciones.
—Mañana vendrás, tío Pablo, ¿verdad?—le decían los chicos.
—Sí, vendré.
Y Elizabide el Vagabundo se marchó a su casa y pensó en Maintoni y
soñó con ella. La veía en su imaginación tal cual era: chiquitilla, esbelta,
con sus ojos negros, brillantes, rodeada de sus sobrinos, que le abrazaban y
le besuqueaban.
Como el mayor de los hijos del boticario estudiaba el tercer año del
bachillerato, Elizabide se dedicó a darle lecciones de francés, y a estas
lecciones se agregó Maintoni.
Elizabide comenzaba a sentirse preocupado con la hermana de su
cuñado, tan serena, tan inmutable; no se comprendía si su alma era un alma
de niña sin deseos ni aspiraciones, o si era una mujer indiferente a todo lo
que no se relacionase con las personas que vivían en su hogar. El
vagabundo la solía mirar absorto.—¿Qué pensará?—se preguntaba. Una
vez se sintió atrevido, y la dijo:
—¿Y usted no piensa casarse, Maintoni?
—¡Yo! ¡casarme!
—¿Por qué no?
—¿Quién va a cuidar de los chicos si me caso? Además, yo ya soy
nesca-zarra (solterona)—contestó ella riéndose.
—¡A los veintisiete años solterona! Entonces yo, que tengo treinta y
ocho, debo de estar en el último grado de la decrepitud.
Maintoni a esto no dijo nada; no hizo más que sonreir.
Aquella noche Elizabide se asombró al ver lo que le preocupaba
Maintoni.
—¿Qué clase de mujer es ésta?—se decía.—De orgullosa no tiene nada,
de romántica tampoco, y sin embargo...
En la orilla del río, cerca de un estrecho desfiladero, brotaba una fuente
que tenía un estanque profundísimo; el agua parecía allí de cristal por lo
inmóvil. Así era quizás el alma de Maintoni—se decía Elizabide—y sin
embargo...—Sin embargo, a pesar de sus definiciones, la preocupación no
se desvanecía; al revés, iba haciéndose mayor.
Llegó el verano; en el jardín de la casa del boticario reuníanse toda la
familia, Maintoni y Elizabide el Vagabundo. Nunca fué éste tan exacto
como entonces, nunca tan dichoso y tan desgraciado al mismo tiempo. Al
anochecer, cuando el cielo se llenaba de estrellas y la luz pálida de Júpiter
brillaba en el firmamento, las conversaciones se hacían más íntimas, más
familiares, coreadas por el canto de los sapos. Maintoni se mostraba más
expansiva, más locuaz.
A las nueve de la noche, cuando se oía el sonar de los cascabeles de la
diligencia que pasaba por el pueblo con un gran farol sobre la capota del
pescante, se disolvía la reunión y Elizabide se marchaba a su casa haciendo
proyectos para el día de mañana, que giraban siempre alrededor de
Maintoni.
A veces, desalentado, se preguntaba:—¿No es imbécil haber recorrido el
mundo para venir a caer en un pueblecillo y enamorarse de una señorita de
aldea? ¡Y quién se atrevía a decirle nada a aquella mujer, tan serena, tan
impasible!
Fué pasando el verano, llegó la época de las fiestas, y el boticario y su
familia se dispusieron a celebrar la romería de Arnazabal como todos los
años.
—¿Tú también vendrás con nosotros?—le preguntó el boticario a su
hermano.
—Yo no.
—¿Por qué no?
—No tengo ganas.
—Bueno, bueno; pero te advierto que te vas a quedar solo, porque hasta
las muchachas vendrán con nosotros.
—¿Y usted también?—dijo Elizabide a Maintoni.
—Sí. ¡Ya lo creo! A mí me gustan mucho las romerías.
—No hagas caso, que no es por eso—replicó el boticario.—Va a ver al
médico de Arnazabal, que es un muchacho joven que el año pasado le hizo
el amor.
—¿Y por qué no?—exclamó Maintoni sonriendo.
Elizabide el Vagabundo palideció, enrojeció; pero no dijo nada.
La víspera de la romería el boticario le volvió a preguntar a su hermano:
—¿Conque vienes o no?
—Bueno, iré—murmuró el vagabundo.
Al día siguiente se levantaron temprano y salieron del pueblo, tomaron
la carretera, y después, siguiendo veredas, atravesando prados cubiertos de
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like