Object Oriented Programming Through Java P Radha Krishna instant download
Object Oriented Programming Through Java P Radha Krishna instant download
Krishna download
https://ebookbell.com/product/object-oriented-programming-
through-java-p-radha-krishna-43702704
https://ebookbell.com/product/java-programming-fundamentals-problem-
solving-through-object-oriented-analysis-and-design-1st-edition-
premchand-s-nair-2406494
https://ebookbell.com/product/object-oriented-programming-through-c-
as-per-the-latest-syllabus-of-jntu-
kakinadaregulation-2014-e-balagurusamy-10959564
https://ebookbell.com/product/objectoriented-programming-in-c-nicolai-
m-josuttis-46086084
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
https://ebookbell.com/product/object-oriented-programminghardmanv1pdf-
amany-fawzy-elgamal-56094468
https://ebookbell.com/product/objectoriented-programming-with-visual-
basicnet-michael-mcmillan-2004060
https://ebookbell.com/product/objectoriented-programming-languages-
interpretation-iain-d-craig-2095070
https://ebookbell.com/product/objectoriented-programming-in-c-7th-
print-with-corrections-lafore-21984516
~
§)) Universities Press COMPUTER SCIENCE
| P Radha Krishna
Object Oriented Programming through
Java”
Other Related Titles Published by Universities Press
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
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
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
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
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.
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 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.
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.
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.
(a) (b)
Derived Class
(a) (b)
ce.
Fig. 1.3 (a) Multiple inheritance graph; (b) an example of multiple inheritan
8 Object Oriented Programming through Java
¢ — Increased productivity
¢ Reduced maintenance
° Standardization
¢ 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.
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.
Geometric shape
Rounded object
Ellipse
Geometric shape
Draw()
Fill()
Rounded object
Draw() Draw()
Fill() Fill()
Circle Ellipse
Draw() Draw()
Fill() Fill()
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.
* 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
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.
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.
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.
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?
Answers
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.
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
Java Java
source code byte code Interpreter
(Sample.java) (Sample.class)
Source code
Source 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.
hardware 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 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
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.
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.
Interpreter
Operating system
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.
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.
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.
// Comments
{
System.out.printin (“This is a simple java program.”);
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
Class File
Java interpreter
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.
oe
ee nec isr = new InputStreamReader(System.in);
int a = Integer.parselnt(br.readLine());
Output:
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:
import java.applet.*;
public class StartApplet extends Applet
{
String message = “ Applet program.”;
6099
String message1 :
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.
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
Applet program.
Writing the message.
provides a debugger tool for debugging programs. Debugging is the process of locating and
fixing errors in programs.
|
public static void main(String args[])
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
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.
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
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)
ebookbell.com