Вот и подошёл к концу наш конкурс! Поздравляем победителей!!! Подробнее.
Проект Programmers.kz и школа hotPen3D2D предлагает Вам курсы по веб-дизайну, веб-программированию и компьютерной графике. Подробности здесь.
- Просмотров: 2304
- Автор: КазКиберГетик
Some Background Information on Java and Object-Orientation
Категория: Программирование » Java » Статьи
Java Unit 1
Some Background Information on Java and Object-Orientation
1.1 Java
1.2 Object-Orientation
1.3 UML
1.4 Downloading and Installing Java and TextPad
1.5 Practical Notes
1.1 Java
What are some of Java’s characteristics that distinguish it from other programming languages? What features does it have that might make it useful in situations where other languages would not be as suitable?
From a technical point of view, Java has one fundamental characteristic which all other important characteristics stem from. Java is a language which is interpreted on a simulated hardware architecture. It is possible to design hardware that runs Java code directly, but in common computing environments such as Windows and Unix, installation of Java on a machine means that the simulation has been installed. When programs run, they run on the simulation. For other languages such as C or C++, compilation results in an executable target file which consists of machine language for the architecture for which the compiler was designed. For Java, the process is still referred to as compilation, but it is not literal compilation. When Java source code is “compiled” the result is “byte code”, which is code which runs on the simulated Java machine.
In such a design, the programming language is merely a layer in a system’s software architecture and it is not dependent on the underlying hardware architecture of the machine. As a result, in theory at least, Java is potentially a “universal” programming language. Versions of Java exist for various hardware architectures. These implementations differ internally. However, the intent is for the Java code generated for these different environments to be exactly the same. Thus, Java programs should be freely portable between them. If a program is written in one environment, no changes in the source code should be necessary in order for it to be compiled or, if already compiled, to be directly run in a different environment. This is the ideal, which is encapsulated in the phrase “Write once, run everywhere”. The reality is that subtle differences in implementations of the Java machine lead to problems which have been encapsulated in the phrase “Write once, debug everywhere”.
As with all system and software design decisions, the nature of Java involves trade-offs. One of the driving forces behind such a language design is the World Wide Web. If a “universal” programming language exists, then programs can be downloaded and run on users’ machines regardless of the hardware involved. Java allows the creation of applets, which are such downloadable programs. No matter what kind of machine is attached to the Internet, if it has Java installed on it, with luck, it will run applets which are accessed on the Internet. The big trade-off in this design is that Java programs are considerably slower than genuine compiled programs which run directly on the hardware of a given machine. Interpreting Java code on a simulated machine may take in the range of ten times as long. As hardware has become faster, and as the World Wide Web has become a desirable medium for distributing programs, this trade-off of speed for portability has become acceptable.
Another one of the design decisions in Java was driven by this desire to download runnable programs. Some languages, such as C and C++, give the programmer the ability to write code which directly accesses memory addresses in a machine’s hardware. This is done by means of pointers. This is not possible in Java. It may seem odd that a modern, advanced language does not allow this. It is possible to write code for linked structures in Java, but not code which relies on memory addresses. Programmers know that programs which directly access memory may do harmful things to a system, whether intentionally or unintentionally. For this reason, direct memory access is undesirable in Java. When users download programs, they want to be sure that these programs cannot do destructive things to their systems which result from direct memory access. Thus, by design, Java supports both portability and safety of programs.
The goal of this book is to give an introduction to programming in the Java language. Java is object-oriented. It is designed to support event-driven programming. In other words, it can be used to create graphical user interfaces which support point-and-click actions. These applications can be both stand-alone programs or applets downloadable from the Internet. Java has basic syntactic features found in structured programming languages, namely sequential execution of blocks of code, conditional execution (if statements), and iterative execution (loops). These syntactical elements will be covered in following units, as well as descriptions of the object-oriented concepts which support more advanced programming.
Experts may argue about the relative technical merits of Java. It must be noted at the outset that it has certain disadvantages for the learner. Java was not designed for teaching or learning purposes. It was designed for building complex applications. In addition to many advanced features within the language itself, it comes with libraries of complete code components which an experienced programmer can use instead of writing components from scratch. Neither the complete syntax nor the libraries can be learned in a one semester course. Much of what is learned at the outset may not seem particularly useful. It is necessary to cover the foundations of object-orientation before it becomes possible to write more interesting applications which include interactive graphical features.
After the foundations have been laid, it becomes apparent that Java is well-suited to its goals. You can create graphical applications which are simply impossible to write in programming languages such as C. It is also the case that code written in Java can be considerably less complicated than code written in C++ to accomplish the same thing. Java was designed from the beginning as an object-oriented language. This gives it an advantage over C++, which was an object-oriented evolution of C. As a final note, the C# language has been created for the same purpose, so Java has a direct competitor which may match or exceed it in various aspects.
Section summary:
1. The Java language is interpreted on a simulated machine architecture.
2. This makes Java source and target code highly portable.
3. This makes it possible to download Java code from the World Wide Web, although Java programs may not run especially quickly.
4. In order to make downloaded programs safe, Java programs do not support direct memory access.
5. Java is an object-oriented language containing the features needed in order to write graphical applications with point-and-click interfaces.
6. Java was designed as a production language, not a teaching language. It contains many features and comes with many libraries.
7. It is possible to do things in Java that cannot be done, or can only be done with difficulty in other languages.
Vocabulary:
1. Interpreted languages, compiled languages.
2. Source code, target code.
3. Pointers, direct memory access.
4. Object-orientation, software applications.
5. Event-driven programming.
6. Point-and-click, graphical user interfaces.
7. Sequential execution.
8. Conditional execution (if statements).
9. Iterative execution (loops).
1.2 Object-Orientation
Programming languages and paradigms have evolved progressively over time. Some of the things that have driven change include: New hardware, which has the capability of supporting new programming paradigms; new problems to be solved, which require new programming capabilities; and limitations in existing systems which are exposed when large or complex projects are developed. Object-oriented programming is one of the more recent programming paradigms. Its development and characteristics reflect these three points. It is a computationally intensive paradigm which could not have been supported by primitive machines; the programming of graphical user interfaces is one area where its use is apparent; and because it has solved at least some of the problems associated with structured programming, its most immediate predecessor, it has largely supplanted it for the development of complex software systems.
Java is an object-oriented language. There are many object-oriented languages, and each implements the paradigm in its own way. It is not the intent of these notes to give a full explanation of object-orientation. It will not even be possible to give a full explanation of all aspects of object-orientation in Java. However, it is desirable to start with some general ideas regarding object-orientation, building a vocabulary for the basic concepts involved. A fuller understanding will arise as the implementation of these concepts in Java is examined, and as more advanced concepts and their implementation are added to the basics.
Two fundamental terms are involved in object-orientation, and will be repeated over and over again. The terms are: Class and object. A class is a model for objects. You could also say that a class is a template, or pattern for objects. To be more concrete, a class is a piece of computer code which gives the complete specifications for objects. The class definition is part of a program’s source code. During the course of a program run it is possible to make a call which causes an object to be created according to the specifications of a given class. An object can be referred to as an instance of this class. A program may use more than one class, and more than one instance of any of these classes may be created during the course of a program run. The work of the program consists of manipulating these objects.
Two additional concepts are involved in object-orientation. Computer programs include sequences of instructions which belong together and can be executed to do some specific thing. In object-oriented programming, these are referred to as methods. Methods are part of a class definition. Computer programs also include declarations of data, such as numbers, sequences of characters, etc., which are to be manipulated. In their simplest form, these are variables. Variables are symbolic names which can be used to refer to stored quantities or values in a program. Different kinds of variables can be used in different places in a program. The variables associated with classes and objects are called instance variables, and like methods, they are part of a class definition.
Although both appear in the class definition, methods and instance variables are treated quite differently in the object-oriented paradigm. In a program there may be more than one instance of more than one class. The following distinction between methods and instance variables applies: There is no need at run time for each instance of a class to get its own copy of method code. Methods are defined in the class and are shared by all objects of that class that are in existence in a program at a given time. Thus, the methods for all objects of a class are exactly the same. However, when objects of a class are created, they get their own copies of the instance variables. Each object of a class gets the same set of variables, but different objects can have different values for the variables.
So, what’s the relationship between methods and instance variables? A fundamental aspect of the object-oriented paradigm is referred to as encapsulation. Each object has its own copies of the instance variables. The values of these variables can be accessed or changed during the course of a program run in only one way: by calling a method which has the purpose of revealing or changing the value of the instance variable. This enforces a strong discipline on programmers. It is not possible at random points in program code to simply change instance variable values in a way that may seem convenient at the moment. Changes can only be made within the framework of encapsulation. Undisciplined changing of data values was considered one of the weaknesses of structured programming. This is corrected in object-oriented programming.
Here is a simple graphical representation of an object, showing the instance variables it contains and the methods it uses.

Figure 1. Instance variables and methods.
A handy way of remembering the meaning of the figure is by thinking of the object as a fried egg. Once the object is created, a program only has access to the yolk through the white. It is important to understand that the programmer making use of the object needs to know what methods are available for manipulating it. However, it is not necessary to know how the method code works. Although the existence of some instance variables may be clear, the programmer does not need to know how they are implemented, and does not need to know all of the instance variables in order to make use of the object. In this sense, the object can be though of as a black box. The programmer can do certain things to it, with certain results expected, but how these results are accomplished is hidden. The methods provide an interface to the instance variables and their values contained inside the object.
Section summary:
1. Object-orientation relies on advanced hardware capabilities, solves problems that could not be solved with earlier programming paradigms, and addresses some of the shortcomings of previous paradigms.
2. Java implements the object-oriented paradigm, and basic object-oriented terms and ideas are helpful in explaining Java.
3. Classes and objects are two of the underlying concepts of object-orientation.
4. Methods and variables are two additional key concepts of object-orientation.
5. When objects are created from a class definition, they share the code for methods, but they each get their own copies of the instance variables.
6. Objects encapsulate their instance variables. The values of the variables can only be accessed or changed if there is a method in the class that permits it.
7. A programmer using an object only has access through the methods, and does not need to know how the methods work or all of the instance variables there might be.
Vocabulary:
1. Paradigm.
2. Computationally intensive.
3. Classes, objects.
4. Methods, instance variables.
5. Encapsulation.
1.3 An Introduction to UML Notation
Depending on the source, the acronym UML is said to stand for “unified modeling language” or “universal modeling language”. In any case, it is a set of conventions that can be used to diagram object-oriented software. It is possible to pictorially represent things like classes and their methods and instance variables; objects of those classes; relationships between classes; and so on. These notes will not give complete coverage of UML. However, at various points in the presentation of Java it may be helpful to represent an idea or relationship visually. In those cases, the corresponding UML notation will be introduced and used for that purpose.
UML has a vocabulary as well as a set of visual symbols which are used to represent object-oriented components. The terms “class” and “object” have already been used in these notes. These terms are used to mean the same thing in UML. The terms “instance variable” and “method” have already been introduced. The corresponding terms in UML are “attribute” and “operation”. There is more than one object-oriented language. UML is neutral. An object-oriented program in any of these languages could be described using UML terminology.
Since this book only covers Java, the terms “instance variable” and “method” will continue to be used. It should be noted that in the official Java documentation, the term “field” is used for “instance variable”. Since this is the term chosen by the language designers, in some sense it may be more technically correct. However, the term “field” may be confusing because it has other uses in various programming environments. “Instance variable” will be used instead because it is more descriptive.
In order to illustrate UML, it is necessary to have an example. It is possible to introduce such an example and talk about object-oriented ideas without even knowing any Java. The example which will be continued throughout the notes is based on the following idea: It is possible to store seeds in a cup. This may seem a little impractical. You typically think of a cup as containing a liquid, and it’s not clear what kinds of interesting programs you might write involving cups and seeds. Any introductory example of a class would tend to be impractical anyway. The cup and seed example is given because it is a component of a game program which is developed later on in the notes.
Classes and objects are represented using rectangles in UML. Relationships are represented using labels, lines, arrowheads, and other symbols. In its simplest form, a class can be represented by a rectangle containing the name of the class. The name is capitalized and given in bold face. For example, this would represent the Cup class:

An object of a given class would have a name of its own. Say an instance is known as “my coffee mug”. It is also represented by a rectangle. The name is not capitalized. It is followed by a colon and the name of the class it is an instance of. All of this is underlined. For example:

The relationship between the class and the object can be graphically shown with an arrow. It turns out that in UML different kinds of relationships are shown with different kinds of arrows, so the form of the arrow is important. This relationship is shown with a dashed arrow with an open, or feathered arrowhead. The arrow points from the object to the class.

More detail about a class can be given by including its attributes and operations in the diagram. In general, such a class diagram takes this form:

To be specific, let the Cup class have one instance variable, named seedCount. Let the class have two methods, setSeedCount() and getSeedCount(). Let the seedCount be an integer, and when a new instance of the class is created, let its seedCount be initialized to the value 0. The setSeedCount() method assigns a value to the seedCount of an object. The getSeedCount() method returns the value currently stored in the seedCount variable, whatever that may be. This information is shown in this more complete form of the class diagram:

It is also possible to give even more detail, including information about the parameter of the setSeedCount() method, ranges of valid values, or other information, for example. The diagrams are used to document a software system, a program, or its components. The level of detail included should be gauged to be helpful to the intended reader of the diagram, whether a designer, a programmer, or a program user.
Section summary:
- UML is used for diagramming object-oriented programs.
- UML has a vocabulary for the components of classes.
- Java has its own, parallel vocabulary for the components of classes.
- The cup and seed example is used for the purposes of illustration.
- In UML classes and objects are represented by rectangles and relationships are represented by arrows and other symbols and labels.
- A simple class diagram is a rectangle containing the capitalized name of the class in bold face.
- A simple object diagram is a rectangle containing the name of the object followed by a colon and the name of its class, all in bold face.
- The relationship between an object and its class can be shown by a dashed arrow with an open arrowhead from the object to the class.
- A more complete class diagram includes the class’s attributes and operations, possibly along with more detailed information.
- The level of detail in diagrams can vary.
Vocabulary:
- UML.
- Attribute.
- Instance variable.
- Field.
- Operation.
- Method.
1.4 Downloading and Installing Java and TextPad
In order to program in Java it is necessary to have a Java compiler. It is possible to download the Sun Microsystems compiler from the Web for free. TextPad is an editor that can be downloaded for free evaluation and eventual purchase if desired. It has been designed to work with Sun’s Java software. If Java is installed first and then TextPad, using the default downloading instructions, TextPad’s Tools menu should contain active options to compile and run Java applications and applets.
Java can be found at this address:
http://java.sun.com/j2se/1.5.0/download.jsp
The portion of the page for the compiler looks like this:
|
JDK 5.0 Update 4 includes the JVM technology |
|
|
|
The J2SE Development Kit (JDK) supports creating J2SE applications. More info... |
|
|
|
|
|
Installation Instructions ReadMe ReleaseNotes |
When you click on the link “Download JDK 5.0 Update 4” you will first encounter a license agreement. After that you will arrive at a page containing links for versions of the software for various kinds of computer. The standard version for a Windows machine is the first. What you want to do is an offline installation. This means that the software will be downloaded to your computer, and from there you double click on the icon to begin the installation process locally. If you are working in a different environment, one of the other links may be appropriate. Feel free to explore the Sun Web site for additional information, such as Java documentation and tutorials. It is not possible to cover all of these things here.
TextPad can be found at this address:
http://www.textpad.com/download/index.html
Follow the directions given on the TextPad Web page. If you have problems, follow this sequence of links:
Support, FAQ, java
Virtually all questions are answered there concerning problems with making TextPad work with Java. For example, if you download and install TextPad and Java in the wrong order, directions on how to get them to work together without installing again are given here. Answers to other questions are also provided. If the instructions are not clear or if you have problems that seem insurmountable, you may decide to use an integrated Java package, whether downloaded for free from the Web, or purchased. Nothing in this set of notes relies on special features of Java, so virtually any version should do.
Section summary:
1. Both Java and TextPad can be downloaded from the Web.
2. If installed in that order, TextPad will contain tools for compiling and running Java programs.
Vocabulary:
1. Download.
2. Install.
1.5 Some Practical Notes on Editing, Compiling, and Running Java Programs
There are several details concerning the naming of Java program files that have to be remembered. They are listed here with explanations:
1. Java program files have to be saved with the extension .java.
2. We have not yet taken a look at the code for a Java program. However, at the top of every program there will be a line of code of this form:
public class Name_of_program
The name of the file that the program is saved in has to agree exactly with the name that appears in this line of code within the program. The first letter of the name is capitalized within the program, and the first letter of the name of the file also has to be capitalized. In other words, in order to be valid, a program that started with the line of code given above would have to be saved with this name:
Name_of_program.java
3. Java is completely case sensitive. Microsoft Windows is not fully case sensitive. This can lead to problems. If you save a file in Windows with a small letter and then try to change the file name to use a capital letter, Windows may not allow it, telling you “A file with this name already exists.” If this happens, save the file under a temporary name, remove the copy with the name incorrectly capitalized, and rename the temporary file with the correctly capitalized name.
If you are using TextPad as your programming environment, the following points apply:
1. Under Tools in the TextPad menu you will find 3 options related to Java: Compile Java, Run Java Application, and Run Java Applet. For the time being we are interested in compiling and running applications. Applets come later.
2. Under Tools in the TextPad menu you will also see a plain “Run…” option. This is mentioned only because you will probably mistakenly try to use this once. Using this option to try and run a Java program will either bring up a dialog box asking what application to run, or an error message. You need to make sure you’re trying to run your programs with the Run Java Application option.
3. To test compiling and running Java programs in TextPad, do the following: Download copies of MyTerminalIO.java and FirstProg.java and save them in the same location on your machine. This can be on a diskette, on the C: drive, or in some folder on either. You may also choose to type in the program using TextPad. The code is shown below for reference. It should be saved in a file named FirstProg.java.
public class FirstProg
{
public static void main(String[] args)
{
MyTerminalIO myterminal = new MyTerminalIO();
myterminal.println("Hello World");
}
}
4. Then click the Compile Java menu item. This may take several seconds. A successful compilation will simply end showing the program file on the screen. An unsuccessful compilation shows a new screen with the error messages for the compilation. This sample program contains no errors as given. If you get compiler errors, make sure the copy of MyTerminalIO.java is in the same location, check to make sure you have correctly downloaded or entered the code and saved the file under the correct name, and then try compiling again.
5. After a successful compilation you can then take the Run Java Application option in the menu. This should bring up a Window with the program output in it.
6. You may unintentionally make a mistake when entering the program, or if not, you may intentionally make one in order to see what the compiler does. What appears in the editor is a listing of errors by line number along with relatively cryptic explanations. If the software installation is completely functional, you should be able to jump directly to the line in the source program that has the problem by clicking on the error message. If this feature isn’t working correctly, just note the line number, switch to the source code file by selecting from the list in the upper left hand frame in TextPad and then go to the line manually. The current line number is shown at the bottom of the editor screen.
7. If your computer is connected to a printer, you can print program source files directly out of TextPad through the File option in the menu.
8. Printing output involves an extra step. The output window does not have menu options. However, it is possible to select and copy the window contents using the mouse. Then open a new TextPad document, and do edit/paste into it. From there you can print using the menu options as usual.
Section summary:
1. Java program files have to match the class name within them and have to have the .java extension. Java is fully case sensitive.
2. The TextPad menu includes options to compile and run Java programs.
3. It is possible to print both source code and program output.
Vocabulary:
1. Extension.
2. Capitalized.
3. Case sensitive.
4. Compile Java, Run Java Application.
Download MyTerminalIO class
Author: Kirk Scott
Мы рекомендуем Вам зарегистрироваться либо войти на сайт под своим именем.




