Базы данныхИнтернетКомпьютерыОперационные системыПрограммированиеСетиСвязьРазное
Поиск по сайту:
Подпишись на рассылку:

Назад в раздел

Chapter 1 -- An Overview of Java

Chapter 1

An Overview of Java


CONTENTS


Introduction

If you have purchased this book, you are probably planning to program with Java. There are many reasons for using Java as your programming language. You might want to learn an object-oriented programming language, and maybe you've heard that Java is simple to use. You might have come across some interesting applets while browsing the Internet (if you're using a Java-capable browser), and perhaps you want to learn to write applets of your own and add them to your Internet or intranet HTML documents. You might want to learn how to add Internet functionality to your C applications or how to use Java to write full-fledged applications that are portable. This book helps you accomplish any and all of these goals.

This overview introduces the many features of Java and explains why they are important to you, the Java programmer. It is worthwhile for you to understand the richness and usefulness of Java before getting into the specifics of the Java environment and language.

Java is an interpreted language that is similar, superficially, to C++, but different in many important ways. Java was originally intended to be an extension of the C compiler but has been completely rebuilt from the ground up to be a smaller, portable, purely object-oriented language that eliminates many of the sources of bugs and complexities common in C++.

A Brief History of Java

Java has been around since 1991, developed by a small team of Sun Microsystems developers in a project originally called the Green project. The intent of the project was to develop a platform-independent software technology that would be used in the consumer electronics industry. The language that the team created was originally called Oak.

The first implementation of Oak was in a PDA-type device called Star Seven (*7) that consisted of the Oak language, an operating system called GreenOS, a user interface, and hardware. The name *7 was derived from the telephone sequence that was used in the team's office and that was dialed in order to answer any ringing telephone from any other phone in the office. This PDA-type device was intended to be sold to consumer electronics manufacturers who would distribute the boxes under their company name. In 1993, the team, then incorporated as FirstPerson, Inc., decided to gear their technology toward a new implementation for which demand was building in the entertainment industry-interactive television. They proposed their technology to Time Warner as an operating system for set-top boxes and video-on-demand technology that would decode the data stream that Time Warner would be sending to television sets around the country. In June of 1993, Time Warner selected Silicon Graphics' technology over Sun's. A later deal fell apart and FirstPerson decided to disband. Half of the members of the original FirstPerson team continued to work with the Oak technology, however, applying it to multimedia and network computing.

Around the time the FirstPerson project was floundering in consumer electronics, a new craze was gaining momentum in America; the craze was called "Web surfing." The World Wide Web, a name applied to the Internet's millions of linked HTML documents was suddenly becoming popular for use by the masses. The reason for this was the introduction of a graphical Web browser called Mosaic, developed by ncSA. The browser simplified Web browsing by combining text and graphics into a single interface to eliminate the need for users to learn many confusing UNIX and DOS commands. Navigating around the Web was much easier using Mosaic.

It has only been since 1994 that Oak technology has been applied to the Web. In 1994, two Sun developers created the first version of HotJava, then called WebRunner, which is a graphical browser for the Web that exists today. The browser was coded entirely in the Oak language, by this time called Java. Soon after, the Java compiler was rewritten in the Java language from its original C code, thus proving that Java could be used effectively as an application language. Sun introduced Java in May 1995 at the SunWorld 95 convention.

Web surfing has become an enormously popular practice among millions of computer users. Until Java, however, the content of information on the Internet has been a bland series of HTML documents. Web users are hungry for applications that are interactive, that users can execute no matter what hardware or software platform they are using, and that travel across heterogeneous networks and do not spread viruses to their computers. Java can create such applications.

Applets

On the Internet, Java programs are called applets. Applets are Java applications that are embedded inside HTML files and can be downloaded into a Java-capable browser with the click of a mouse. Applets are different from regular Java applications. A Java application simply has a single main() method that indicates to the Java runtime system that it is an application. A Java applet is an application that includes several additional methods that the runtime system uses that tell it how to handle the applet, such as what to do when a user clicks an applet icon and how it looks on a page.

Before your browser's runtime Java interpreter downloads and executes the applet's code, the Java interpreter verifies the code's integrity. Java is more than a tool to help you write applets, however. It is a new, powerful programming environment.

Java's Features

Sun describes Java as a "simple, object-oriented, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, and dynamic language."

Each of the features mentioned in this quotation from Sun's Web page is an important part of the Java development environment as well as a critical requirement for Web programming. The combination of these features makes Java a powerful and useful programming language that empowers you, the programmer, with the tools you need to easily create powerful programs for today's distributed environments.

Simple

Java is simple to use for three main reasons: First, Java is familiar to you if you know C. Second, Java eliminates components of C that cause bugs and memory leaks and replaces their functionality with more efficient solutions and automated tasks, so you have a lot less debugging to worry about than you would using C or C++. Third, Java provides a powerful set of pre-tested class libraries that give you the ability to use their advanced features with just a few additional lines of code.

Object-Oriented

Java is an object-oriented programming language that uses software objects called classes and is based upon reusable, extensible code. This means that you can use Java's classes, which are sets of variables and methods, as templates to create other classes with added functionality without rewriting the code from the parent classes or superclasses. If you plan your application's class hierarchy well, your application will be small and easy to develop. The hierarchy of classes is explained later in this chapter.

Robust

Java is robust because the language removes the use of pointers and the Java runtime system manages memory for you. The problems with pointers in C and C++ was that pointers directly addressed memory space. In a distributed environment like the Internet, when code is downloaded to diverse systems, there is no way of knowing for sure that memory space addressed by pointers is not occupied by the system. Overwriting this memory space could crash a system. Java also gives you automatic bounds checking for arrays, so they cannot index address space not allocated to the array. Automatic memory management is done using the Garbage Collector, which is explained in detail in Chapter 4, "Creating Your Own Objects."

Interpreted

Java is interpreted, so your development cycle is much faster. As you learn later when the Java interpreter is discussed, you need only to compile for a single, virtual machine and your code can run on any hardware platform that has the Java interpreter ported to it.

Secure

Java is secure, so you can download Java programs from anywhere with confidence that they will not damage your system. Java provides extensive compile-time checking, followed by a second, multilayered level of runtime checking. Java's security structure is described in detail in Chapter 19, "Security Issues."

Architecture Neutral

Java is architecture neutral, so your applications are portable across multiple platforms. Java's applications are written and compiled into bytecode for Java's virtual machine, which emulates an actual hardware chip. Bytecode is converted to binary machine code by the Java interpreter installed at the client, so applications need not be written for individual platforms and then ported from platform to platform. Java additionally ensures that your applications are the same on every platform by strictly defining the sizes of its basic data types and the behavior of its arithmetic operators. Operator overloading, the process of modifying the behavior of operators, is prohibited by Java.

High Performance

Java is "high performance" because its bytecode is efficient and has multithreading built in for applications that need to perform multiple concurrent activities. Although threads still require the use of classes, Java balances the addition of thread synchronization between the language and class levels. Java's bytecode is efficient because it is compiled to an intermediate level that is near enough to native machine code that performance is not significantly sacrificed when the Java bytecode is run by the interpreter.

Dynamic

Java is dynamic, so your applications are adaptable to changing environments because Java's architecture allows you to dynamically load classes at runtime from anywhere on the network, which means that you can add functionality to existing applications by simply linking in new classes. For example, if your applet is being run by a browser that doesn't have one of the classes included in your applet's bytecode, the browser can download the appropriate class from the server that is storing your applet, check the bytecode, and execute it. This is assuming your browser has not been configured with strict security. Chapter 19 covers browser security.

The Fundamentals of the Java Language

This chapter introduces you to the basic concepts and functions of the Java programming language and gives you brief examples to illustrate important points. The later, more advanced chapters guide you through extensive samples of code, and so the examples in this chapter are short. By the end of this chapter, you should have a basic understanding of the Java language and be ready to explore in detail Java's class libraries in Chapter 3, "An Introduction to Java Classes."

Java programming will be fairly easy for you if you have had experience with C++ because Java is designed to look and feel like C++. If you are an experienced C programmer, you will have to let go of some old habits to program Java, however, as you will discover later in this chapter. Please do not be concerned if you have little or no experience in programming-this book assumes no prior knowledge of C++. You may need to read through the chapters more slowly and carefully than an experienced programmer.

Java as an Object-Oriented Language

Java's class structure is made up of the following major components: classes, hierarchy, variables, methods, and inheritance.

Classes

The key to understanding Java's object-oriented design is understanding what classes are and what you can do with them. Classes are templates that you use to create actual objects. The instructions contained in a class are used to create one or more objects, which can be called instances of classes in Java. When you create an object from a class, you instantiate the object, which means you create an instance of the class. The words instances and objects are used interchangeably throughout the discussions of classes in this book, depending on the context of the sentence in which they're used.

In object-oriented programming, you can think of an object as you would any real-world object, for example, a rectangle. The actual rectangle would be an instance of the class Rectangle.

A very rudimentary declaration of a class is as follows:

class  classname {
//class instructions
}

The instructions in a class are made of two basic components: variables that hold data, and methods that manipulate the data.

Before you begin creating the classes in your application, you must design the class structure. Java's class structure is organized into a hierarchy.

Hierarchy

Classes are organized into a hierarchy to allow you to easily reuse code. When you write a Java program, first determine which objects you'll need to use in your code. Then determine what variables and methods the object's class must store. When you know what instructions your classes contain, plan your hierarchy.

Without planning your hierarchy first, you would begin creating a class for each object individually and undoubtedly would find that you are repeating instructions from class to class. In a hierarchy, instructions common to groups of objects are separated out in parent classes, or superclasses, and can be used by all of their subclasses. Therefore, when you plan your hierarchy, you would group objects by the instructions that they have in common and organize them into a hierarchy.

Superclasses are used as templates to create subclasses with variables and methods that make each subclass unique. Each superclass can be a parent to one or many other subclasses. Unlike in C++, a subclass can have only one superclass. Therefore, the Java class hierarchy looks something like the one shown in Figure 1.1.

Figure 1.1: Java class hierarchy.

If a superclass is not defined when a class is declared, the class is automatically made a subclass of Java's Object class. Every class in a Java program is a descendant of Object. Object itself has no superclass.

Variables

Classes store information that describe objects in instance variables. When objects are created from a class, they contain new instances of the class' variables. These instance variables can have values that are different from one object to the next. Values of instance variables are called data. When an instance variable's data is changed, it affects only the individual object. There is a way in Java to assign a variable to a class that, if changed, is changed in all instances of the class. Such a variable is called a static variable, which you learn about later in this chapter in the section called "Static Methods and Variables."

The basic declaration statement of a variable is this:

datatype variablename;

Two variables that might be declared for a rectangle are length and width. They could be declared in one line because they have the same data type. (You explore data types in Table 1.1 of this chapter.) Their declaration statement might be this:

int length, width;

If you created an object from a class with only these two variables declared, the object would simply hold this data. It would not know to draw lines with these values to form a rectangle. Methods must be declared to use the data in variables.

Methods

Methods are functions that must be associated with individual classes. In C and C++ and other procedural languages, functions can be placed anywhere in the code. In Java, they must be stored within classes. Instances of methods are created when instances of classes are created. Unlike variables, methods are not duplicated in objects-their code is stored only in the class.

When an object's method is invoked from its class, it uses the data of variables in the object.

Every method returns a value if it is not declared as void. To declare a method, you use the following statement:

returntype methodname (parameter list) {
    //method code
}

At this point in the chapter, you won't get into coding the method that draws the rectangle. After you've learned the basic coding elements of Java later in this chapter, exercises in coding methods will be more useful.

Inheritance

Variables and methods that are stored in classes in the class hierarchy are inherited by subclasses, so you do not need to re-create them. Objects created from a subclass will contain not only the instances of the variables and methods of the subclass, but also its superclass' variables and methods, as well as those of the parent of its superclass, and so on. When a variable or method is referenced in an object, it is retrieved in a specific order: Java first searches for it in the current class, then, if it is not found, it searches the parent class, and so on.

In summary, objects in your Java program are created from classes that contain variables and methods to describe the object. Classes are organized into a hierarchy in which classes inherit functionality from parent classes, which allows for reusable code. These basic concepts of the structure of Java's object-oriented programming language will become clearer to you as you read through the rest of the sections.

Basic Coding Elements

Your Java code is used to create classes, objects, interfaces, and packages. You'll learn how to create each of these in Chapter 4. This section outlines the elements of the code you need to use to create them.

Your code is written in a series of statements, which can be organized into blocks. These statements contain data and operators, which are components of expressions. You can annotate your code using comments, which makes the code more understandable.

Statements

Any line of code before a semicolon is known as a statement and is executed by the Java interpreter when it hits the semicolon; after executing that statement, the interpreter moves to the next statement. Each statement contains instructions for using data and operators.

Expressions

An expression is a part of a statement that uses data and operators to return a value.

Blocks

A block is a collection of statements enclosed in curly braces. Any variables that you declare and that assign values within a block are erased when the flow of execution leaves the block. The block in which the variable's value exists is called the scope of the variable.

Comments

Comments are used to annotate the code so that a reader can understand the purpose of certain lines and blocks of code. Comments are ignored by the Java compiler. Multiline comments are preceded by /* and are ended with */. Single line comments are preceded by //. The double slash "comments out" text only to the end of a line. A comment would appear as follows:

/*  This declares the length variable for the Rectangle class   */
int length;

or

int length;   //Declares the length variable for the Rectangle class

Data Types

To represent data values in your code you use literals. Literals are described by types, named by identifiers, and stored in variables, which were outlined earlier in the chapter and are explored further in this section.

When you use literals in your code, they appear in their raw form rather than as a result of an expression. Several types of literals are commonly used: numbers, integers, floating points, characters, Booleans, and strings.

Table 1.1 outlines Java's strict definitions of these data types.

Table 1.1. Rules for Java literals.
Literal TypeTypename Rule
NumberNum Can_ be integer, floating point, or character.
Integer Can be decimal, hexadecimal, or octal.
 Byte 8-bit integers between -128 and 127.
 Short 16-bit integers between -32768 and 32767.
 Int 32-bit integers between -2147483648 and 2147483647.
 Long 64-bit integers between -9223372036854775808 and 9223372036854775807 or have L or l appended to them.
 Hex Preceded by 0x or 0X.
 Oct Preceded by 0.
Floating point Any number with a decimal point. Can be made exponential by appending an e or E, followed by the exponent.
 Float 32-bit.
 Double 64-bit.
CharacterChar 16-bit integers represented by a single character and enclosed in single quotes.
  In Java, the Unicode character map is used. The following special characters must be represented by escape sequences:
  backspace      b
  backslash       \
  carriage return  r
  double quote   "
  formfeed        f
  hex number     xhh
  horizontal tab   t
  newline         n
  octal number    00
  question mark  q
  single quote     '
  vertical tab      v
BooleanBoolean Can only be true or false. Are not represented by 0 or 1.
StringString Zero or more characters enclosed in double quotes.

Literals are described by identifiers. Identifiers are sequences of letters and digits, and can also be used to describe variables, methods, and classes. Identifiers can consist of any letter from a to z, underscore, dollar sign, digits from 0 to 9 (except as the first character); identifiers are case-sensitive.

Java has several reserved keywords that are its own identifiers, which cannot be used as identifiers in any way other than that defined by Java, as listed in Table 1.2. Though these words are reserved, not all are used in the most recent release.

Table 1.2. Reserved keywords.
Abstract elseint short
boolean extendsinterface static
break finallong super
byte finallynative switch
case floatnew synchronized
cast fornull this
catch futureoperator throw
char genericouter throws
class gotopackage transient
const ifprivate try
continue implements protectedvar
default importpublic void
do innerrest volatile
double instanceof returnwhile

Operators

Operators are used to compare values. Java has strict definitions of operators. It doesn't allow for overloading, which is a C developer's common practice of changing the behavior of operators.

Java provides two types of operators: binary and unary. Binary operators are used to compare two values. Unary operators use a single value, for example:

a >= b
a++

The first example uses a binary operator, >=, which compares variables a and b. The second is a unary operator, ++, which increments the value of a by one.

All of Java's binary and unary operators can be found in Table 1.3. They are organized according to the precedence with which they are performed.

Table 1.3. Binary and unary operators.
OperatorDescription
., (), [] Precedence overriding decimal, parentheses, brackets
!, ~, ++, -- Boolean negation, bitwise complement, increment, decrement
*, /, % Multiplication, division, modulus
+, - Addition, subtraction or unary negation
<<, >>, >>> Left shift, right shift, zero-fill right shift
<, <=, >, >= Less than, less than or equal to, greater than, greater than or equal to
==, != Equals, is not equal to
& Bitwise or Boolean AND
^ Bitwise or Boolean XOR
| Bitwise or Boolean OR
&& Evaluation AND, Logical AND
|| Evaluation OR, Logical OR
?: If…then…else
=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>= Assignment operators
, Comma

Declaring Variables

There are four types of statements to use for variables: declarations, assignments, initializers, and casts.

You must always declare variables before you can use them in your Java program. Variable declarations assign data types to variables. A declaration statement in Java consists of a data type followed by an identifier. Any of the data types listed in the previous table can be used to declare variables, for example:

Boolean IsReady;
float miles;
int x, y, z;
short pages;

Assignments are statements that assign values to variables. These, like declarations, are required before variables can be used. They are called by setting an identifier equal to a value. This value, of course, must be compatible with the data type assigned to the variable identifier. Initializers are assignment statements that are combined with the declaration statement, for example:

Boolean IsReady = false
float miles = 3.62
short pages = 240

If you want certain variable values to remain constant in your code, you can use the final keyword, which ensures that the variable cannot be changed by the code. Its form is this:

final int pages = 500

Casts are statements you use if you need to place a value of one type into a variable of another type. In C++, automatic coercion allows you to do this without declaring that you were aware of this change. In Java, you must explicitly call such an instruction with a cast statement. Cast statements are generally called as follows:

datatype identifier = (datatype) identifier

Java allows casts only between compatible data types.

In this section, you have learned about the data and operators that are used in expressions that are parts of statements. You now understand that statements are organized with blocks and annotated with comments. You have also examined some basic statements that deal with variable declarations. These are the fundamental elements of Java coding.

Flow of Execution

Now that you understand the basic structure and elements of the Java language, you'll see how statements flow through a Java program in this section. By default, the Java interpreter executes statements in sequential order. This section introduces you to some more complex types of statements that alter this flow of execution.

Conditionals

if, if...else, ?:, and switch are four conditional statements that are used often in code. They evaluate an expression and, based on the value of the expression, they control which statements are executed.

The if statements consist of if followed by a test expression. If the test expression returns a true value, the statement or block of statements after the expression is executed. They are structured as follows:

if (test expression) statement;

if...else statements are similar to if statements, but include a false statement that is executed if the test expression returns a false value. They are structured as follows:

if (test expression) true-statement;
else false-statement;

The ?: is a ternary operator that allows you to assign one of two values based on the evaluation of an expression as true or as false. Its form is as follows:

(test expression) ? true-value : false-value

The switch statement evaluates an expression's value and jumps to a statement identified by the literal value of the expression. It saves coding time if there are several values in your statement. Its form is as follows:

switch (expression) {
     case value: statements
     case value: statements
     default: statements
}

Loops

Loops provide you with the ability to repeat certain statements until a condition is met. Java provides three types of loop statements: while, do...while, and for. Three other statements commonly used with loops are break, continue, and labels, but these can be used with other types of Java statements (such as conditionals) as necessary.

The while loop evaluates a condition to see if it is true, and then executes statements and checks the condition again. If the condition is still true, while executes the statements and checks again. This process continues until the condition is evaluated as false. The form is this:

while (expression) true-statements

The do...while loop is similar to while, but do...while executes statements before the condition is evaluated. When you use do...while, loop statements are always executed at least once. The form is this:

do statements while (expression)

The for loop allows you to test a range of values in your expression. Its form is generally this:

for (initializer; expression; increment)
statements

The break statement is used to exit loop and conditional statements before meeting a test condition. The continue statement directs execution back to the beginning of a loop without completing all of the loop statements. A label is used to identify a statement so execution can be directed to it with a break or continue statement. A colon (:) must be appended to a label name.

An example of a label is as follows:

variable declarations;
Label:
     while (test expression) {
statement;
if(test expression)  {
continue Label;
}
statement;
     }

Arrays

Arrays create slots that allow you to store a list of variables. Arrays are allocated using the new operator to create the array and assigning it to a variable with =. Arrays are declared as follows:

datatype variable[] = new datatype[number-of-slots];

The first half of the statement declares the variable that holds the array. Your array declarations should end in square brackets. The second half creates the array and assigns it to the variable.

The new modifier automatically initializes your array to false for Boolean arrays, 0 for numeric arrays, for character arrays, and null for all other types of arrays. You can choose to initialize the array on the same line as the declaration, as shown here:

datatype [] = {element1, element2, element3, etc.}

Using Classes, Objects, and Interfaces

Every Java application is essentially a class that contains the main() method. This section discusses briefly how to create and use classes, objects, and interfaces in Java applications. You'll learn about many additional elements of the Java programming language that are important to know when using classes and objects.

Creating Classes

The first step in creating an object in your application is to create its class. The following form is used to define a class:

class classname [extends classname] [implements interface] {
     [variable declaration;]
     [method declaration;]
}

In this form, the classname is the name of the new class; extends classname is where the parent class of a subclass would be named, after the word extends. The implements interface defines an interface used by the class (interfaces are covered later in the chapter). If you do not want the compiler to allow your class to be subclassed, you can precede your class statement with the word final. If you wish to create a class that must be subclassed, you would precede the class with the word abstract.

You explored variable declaration in detail in the first section. Keep in mind that variables must be initialized before being used in methods. Now you'll learn how methods are declared. Methods generally use the following form:

[Modifiers] return-type method-name (parameter-list) {
     [statements;]
}

The return type specifies the type of data or class that is returned when the method is run. The void return type is used when no value is returned. When naming the method, you must follow the same rules for naming classes and variables described earlier in the chapter. You must always enclose the parameter list in parentheses even if the parentheses are empty. The parameter list contains the types and variable names of all variables that you want to pass to the method. The statements are the code of your method.

Overloaded Methods

You use overloaded methods in your code when you need to call a method with different sets of parameter lists. Methods that allow flexibility in the parameters they use can be called from different parts of your program with different variables. Java's API classes, discussed in Chapter 3, use overloaded methods. To allow a different type of parameter information to be passed to your method, repeat the method in your code with the alternate parameter list included, as follows:

returnvalue methodname (parameter list 1)
returnvalue methodname (parameter list 2)

When the method is called and parameters are passed to it, Java determines which version of the method has a parameter list that most closely matches the parameters passed and executes it.

Static Methods and Variables

Static methods and variables are similar to the methods and variables already discussed, but they are a part of the class and do not require you to create an object to use them. Static variables are common to all instances created from the class they are stored in. When the value of a static variable in a class is changed, it is likewise changed for all instances of the class.

You might want to use static methods to provide utilities for the rest of your application. Statics can also be used with initializers to create constant data that is used by all instances of the class. All static statements-whether they are variables, methods, or initializers-are preceded by the word static.

Constructors

Constructors are methods that you use when you create objects. They take the function of initializers a step further. They have the same name as the class and return no value. A default constructor is automatically created by the Java compiler if you don't specify one in your code. It is called when an object is created without parameters. Constructors, like methods, can be overloaded.

Creating Objects

After you have a class that has variables and methods stored, you can create objects from it. You can think of an object as an area of memory that is allocated for an object's instance variables. To create the object and automatically allocate memory for it, always use the operator new. This new operator creates the object of the type specified and calls the constructor that is appropriate for the parameters passed in the parameter list. A reference is then made by Java to the new object. The form of an object creation is generally as follows:

classname reference-variable;
reference-variable = new classname (parameter-list)

The first line declares a variable that holds the reference to the object (references are explained in the next section). The second line creates a new object and assigns the variable to it. If parameters are passed, the appropriate constructor is called. If no parameters are passed, the object's default constructor is called.

References

References, which are created when objects are created, can be used to access variables and methods in other objects. References are used by other methods from other objects in the following form:

reference-variable.instance-variable
reference-variable.instance-method

Variables and methods stored in other objects are called by using the reference variable followed by a dot and the name of the foreign variable or method.

You use the reference value in comparisons. The operators used in references are ==, !=, and instanceof. The == and != operators can be used to tell whether two references refer to the same object or whether a reference does not refer to any object (such a case would return a null value). The instanceof operator is used to determine whether an object was created from a certain class or one of its subclasses. If a statement comparing an object to a class using instanceof returns true, that object is in fact an instance of the specified class.

If you are a C programmer, note that pointers are replaced by references in Java. This is explained in greater detail later in the book.

Class Inheritance

When a subclass is defined, it must indicate the superclass it is being created from. This is done with the extends modifier. The form of a subclass declaration is this:

class subclassname extends superclassname {
     //new instructions
}

If a subclass uses a method from a superclass but adds functionality to it, it overrides the method. In Java, you do not need to duplicate the code in the other class. Just refer to the original method in the superclass with super.

null, this, and super Variables

Every class has the following three special variables: null, this, and super.

The null variable has a reference that points to nothing. You may use this reference to assign no value to a variable's identifier. null variables are empty containers that represent the absence of an object. To create an empty container, the following form is used:

datatype variablename = null;

The this variable has a reference to the actual object. A class can refer to itself using this. To refer to itself, a class uses the following form:

methodname(this);

The super variable has a reference to the superclass type of the class. You might wish to reference the superclass type when creating objects. Just precede your variables with the word super:

super (x,y)

Encapsulation

Encapsulation is used to hide methods and variables in your classes from being accessed from foreign methods. To encapsulate variables and methods in your classes, precede their declarations with the keyword private. Private variables and methods can be seen only within a class. Subclasses or external methods cannot see them.

Access Modifiers

The private modifier is one of three types of access modifiers that control the way foreign methods see your variables, methods, and classes. The others are public and protected.

Any foreign methods are able to access variables and methods preceded by the word public. There can be only one public class per source file. This class must have the same name as the source file. Applets, which are explained in detail in a later chapter, must contain at least one public class that is a subclass of the Java.Applet package.

Protected variables and methods can be used only within a class or its subclasses. Foreign methods cannot access protected variables and methods.

Creating Interfaces

Interfaces in Java are unlike interfaces in any other language. They provide a second form of inheritance. Because Java does not allow you to inherit from more than one superclass, Java lets you implement interfaces, which provides you with the functionality that inheritance from multiple superclasses would. Using interfaces, your object can use methods and variables from classes that are outside of its class hierarchy.

Interfaces are structured as entirely abstract classes with variables that are static and final and contain methods without code to implement them. Interfaces can inherit from an unlimited number of other interfaces. They are structured the same way in which classes are structured, except with the keyword interface instead of class:

interface interfacename [extends interfacename] {
     [variable declaration;]
     [method declaration;]
}

Interfaces are implemented by classes and can extend other interfaces. Classes that implement interfaces include the code for the methods of interfaces. These classes can implement more than one interface.

Interfaces can be used to conjoin several unrelated classes and have them respond to the same methods. For example, using interfaces, several shape classes such as rectangle, triangle, and circle can respond to a method called MoveLeft(), which would repaint the shape a certain distance to the left of the original location. In such a case, MoveLeft() would be declared in the interface, but its code would be stored in the class that implements the interface.

Packages

Java provides you with several libraries of classes which are called packages. You can use any of the classes in these packages by importing them into your application. Additionally, you may wish to package related classes you create so they can be reused in other applications. Packages are presented in detail in Chapter 3.

How Java Differs from C++

Now that you have a basic understanding of creating and working with classes, objects, and interfaces, you should be ready for Chapter 2, "Getting Started," that introduces you to the Java development environment. Before proceeding to Chapter 2, read through this section; it explains the differences between Java and C++. It is important that you understand what Java has changed and the reasons for these changes.

Java functionality differs from that of C and C++ in many ways. As I discussed earlier in this chapter, these changes are intended to create an object-oriented language that eliminates many of the opportunities for bugs and memory leaks that are common in C and C++. If you have experience in C or C++ programming, some of Java's changes may take some getting used to. The following list touches on the most important of these changes:

  • Java is an interpreted language, not a compiled language as is C++. This means that compiling is done by an interpreter before execution.
  • Java uses classes or interfaces to build composite data types instead of structures and unions, as in C++. This ensures portability.
  • There are no #defines in Java because the development team felt that using #defines advocates coding that is hard to read.
  • Command-line arguments are different in Java. They are arrays of strings that contain the arguments. Through a mechanism known as varargs, C++ allows you to provide a variable number of arguments to a function. This mechanism is not supported by the Java language.
  • Java has no header files. Instead, Java uses interfaces that show only the methods and final, or constant, variables instead of the entire structure.
  • Pointers, one of the primary features that introduce bugs and memory leaks into programs, are removed in Java. By getting rid of structures and encapsulating arrays through references, Java has attempted to get rid of the original reasoning behind pointers. Java does not allow you to construct a reference to anonymous memory, so it produces robust, efficient code much less prone to bugs, memory leaks, and corruption.
  • Java has replaced multiple inheritance by interfaces to avoid problems with fragile superclasses.
  • To ensure a purely object-oriented structure, there are no individual functions in Java. Functions must be encapsulated in a class.
  • While Java retains goto as a reserved word, it is not implemented or supported by the Java language.
  • Java has strict definition of operators. It doesn't allow for operator overloading.
  • Automatic coercion, which is a common cause of inaccuracy in C++, would allow you to place an incompatible variable into another without declaring that you were aware of this change. In Java, in order to store a variable of one type in a variable of another type, you must explicitly call it with a cast statement.
  • Java programs crash reliably and obviously, whereas crashes in C and C++ programs are not as apparent.
  • Java implements a new function called automatic garbage collection. The Java runtime system keeps track of all references to an object until the object is no longer needed. When there are no more references to an object, it makes it available for garbage collection.
  • Java also implements automatic memory management and thread controls. Although threads still require the use of classes, Java balances the addition of thread synchronization between the language and class levels. For example, garbage collection is run as a background process (or low-priority thread). It remains quiet until there is either a sufficient pause in the execution of foreground threads for it to run, or the system explicitly requires the use of memory which is taken up by unreferenced classes.
  • The Java language provides a finally statement for use with Java exceptions. The finally statement delimits a block of code used to release system resources and perform various other cleanup operations after the try statement.
  • Java strings are first-class objects. They are a class provided in the java.lang package. This provides consistency and predictability in string functions.

Summary

This concludes the introduction to the Java language. As you read through the rest of this book, you may need to refer to some sections in this chapter to be sure you understand the basic elements of Java that have been outlined for you. In the next chapter, you'll learn about Java's packages in detail, as well as more complex programming elements that these packages make easier.


Next Contents



  • Главная
  • Новости
  • Новинки
  • Скрипты
  • Форум
  • Ссылки
  • О сайте




  • Emanual.ru – это сайт, посвящённый всем значимым событиям в IT-индустрии: новейшие разработки, уникальные методы и горячие новости! Тонны информации, полезной как для обычных пользователей, так и для самых продвинутых программистов! Интересные обсуждения на актуальные темы и огромная аудитория, которая может быть интересна широкому кругу рекламодателей. У нас вы узнаете всё о компьютерах, базах данных, операционных системах, сетях, инфраструктурах, связях и программированию на популярных языках!
     Copyright © 2001-2024
    Реклама на сайте