随笔 - 303  文章 - 883  trackbacks - 0
<2007年2月>
28293031123
45678910
11121314151617
18192021222324
25262728123
45678910

欢迎光临! 
闲聊 QQ:1074961813

随笔分类(357)

我管理的群

公共blog

  • n维空间
  • Email : java3d@126.com 群 : 12999758

参与管理的论坛

好友的blog

我的其他blog

朋友的网站

搜索

  •  

最新评论

Programming in Java


1. Introduction

Java® is an object-oriented programming language that resembles C++ in many respects. One of the major differences is that Java® programs are intended to be architecture-neutral i.e. a Java® program should, in theory, be able to run on a Unix® workstation, a PC or a Macintosh® without recompilation. In C++, we compiled our programs into machine-dependent object code that was linked to produce an executable. By contrast, Java® programs are compiled into machine-independent byte code. The compiled program is then run within a Java® interpreter, which is responsible for executing the byte code instructions. The Java® interpreter is typically referred to as the Java® Virtual Machine, and it must be present on each computer that runs the program.
 

 

Java® compiler

 

Java® interpreter

 

myprog.java

-------------->

myprog.class

---------------->

Program output

 

javac

 

java
appletviewer
netscape

 

Follow this link to see Sun Microsystems' overview: About the Java® Technology

It takes time to learn everything about Java® and it is important to set your expectations accordingly. There are two main challenges:

  • Learning the basic syntax of the language.
  • Gaining familiarity with the libraries of reusable software components that are available to Java® programmers, especially the commonly used parts of the Java® Core API (Application Programming Interface).

In the lectures that follow, we will attempt to familiarize you with the basic syntax, and point out the syntactic and semantic differences between Java® and C++. We will also introduce you to some of the more important class libraries. The Java® API is well documented and you should quickly learn how to navigate the online documentation to find the classes that you need.

The Java® language is still evolving. We will be using the Java® 2 platform, which is also known as the Java® Development Kit (JDK). The latest release is Java® 2 version 1.3. Be prepared to encounter bugs in the implementation of the language from time to time. This includes inconsistencies across hardware platforms. Also note that the latest version of Java® is not supported by the Netscape® browser.


2. Online Java® Resources

Here is an online Java® tutorial.

3. Applications and Applets

An application is a stand-alone program that executes independently of a browser. It is usually launched from the command line, using the command line interpreter, java.

An applet is a program that can be embedded in an HTML page. The program can be run by loading the page into a Java®-enabled browser. The JDK includes a tool, called appletviewer, that can also be used to view applets.

A Java® program can be designed to function

  • as an application
  • as an applet
  • both as an application and as an applet

The Hello World Application

Here is an example of a simple Java® application. We make our program an application by writing a class, HelloWorldApp, that contains a function named main(). We can compile our program by typing

    javac HelloWorld.java

This will produce a file named HelloWorldApp.class.

We can run the program as application by typing

   java HelloWorldApp

The command line interpreter looks for a function named main() in the HelloWorldApp class and then executes it.

Points to Note

The .class file gets its name from the name of the class and not the name of the source file. In this example we deliberately gave the source file a different name, but in practice, we will place each class in a separate file with the same name. This convention becomes important when we want to write a class that is publicly accessible.
 

Global functions are not allowed in Java®. This is why we placed our main() function inside our class. We must make our main() function static, since it should not be associated with a particular object, and we must also make it public, since it is the entry point to our program.

HelloWorld.java

class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}



The Hello World Applet

Here is an example of a simple Java® applet. We make our program an applet by writing a class, HelloWorld, that inherits the JApplet class provided in the Java® Swing API. The extends keyword declares that class HelloWorld inherits class JApplet. Before we can refer to the JApplet class, we must declare its existence using the import keyword. Here we have imported the JApplet class, which belongs to the javax.swing package, and we have also imported the Graphics class, which belongs to the java.awt package.

The JApplet class possesses a method named paint(), which it inherits from one of its superclasses. Our HelloWorld class inherits this paint() method when it inherits the JApplet class. The purpose of paint() is to draw the contents of the applet. Unfortunately, the default paint() method that we inherit cannot do anything useful since it has no way of knowing what we want to draw. We must therefore override the default paint() in our HelloWorld class. (Note that while C++ requires the use of the virtual keyword to indicate function overriding, Java® does not require us to inform the compiler that overriding will take place.)

The paint() method receives as an argument a Graphics object, which contains information about where and how we can draw. In this example, we choose to draw the text "Hello World!" at coordinates (50,25) by calling the drawString method.

We can compile our program by typing

    javac HelloWorld.java

This produces a file named HelloWorld.class. We now embed our applet in an HTML file, Hello.html, and we can run it by typing

    appletviewer Hello.html

We can also view Hello.html in a Java®-enabled browser.
 

HelloWorld.java

import javax.swing.JApplet;
import java.awt.Graphics;

public class HelloWorld extends JApplet {
    public void paint(Graphics g) {
        g.drawString("Hello world!", 50, 25);
    }
}
 

Hello.html

<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>

<BODY>
Here is the output of my program:
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML> 


4. Java Basics

Java Data Types

Java® has two main categories of data types: primitive data types and reference data types. Java® does not support the notion of pointers.

Here is a list of primitive data types.

PRIMITIVE DATA TYPE

SIZE IN BYTES / FORMAT

byte

1

char, short

2

int, float 

4

long, double

8

boolean

true or false

 

Reference data types include arrays and classes. Here is an example of a Line class.

Line.java

class Line {

    private int miX1, miX2, miY1, miY2;

    public Line() {
        miX1 = miX2 = miY1 = miY2 = 0;
    }

    public Line(int iX1, int iX2, int iY1, int iY2) {
        miX1 = iX1;
        miX2 = iX2;
        miY1 = iY1;
        miY2 = iY2;
    }
}



Creating Objects - Constructors

In Java®, objects of user defined data types must be dynamically created. In the following example, the first statement declares a Line object, but does not actually create it. The second statement uses the new operator to actually create the object. Note the subtle differences between Java® and C++.

Line line;                        // Declaration of object (does not create object.)
line = new Line();            // Instantiation of object.


Garbage Collection and Finalization

The Java® runtime system provides a garbage collector, which periodically destroys any unused objects in dynamic memory. The Java® garbage collector uses a mark-sweep algorithm. The dynamic memory is first scanned for referenced objects and then all remaining objects are treated as garbage. Prior to deleting an object, the garbage collector will call the object's finalizer, which allows the object to perform an orderly cleanup of any associated system resources, such as open files.

Finalization and garbarge collection happen asynchronously in the background. It is also possible to force these tasks to occur using the System.runFinalization() and System.gc() commands.

A finalizer has the form

    protected void finalize() throws Throwable {
           ...
          // Clean up code for this class here.
          ...
         super.finalize();  // Call the superclass's finalizer (if provided.)
   }



Inheritance

As indicated above, the extends keyword allows us to write classes that inherit the properties and methods of another class.

    class SubClassName extends SuperClassName {
        ...
    }

If a superclass name is not specified, the superclass is assumed to be java.lang.Object. Also, note that each class can have only one immediate superclass i.e. Java® does not support multiple inheritance.


Packages

A package is a group of related classes or interfaces. Each package defines its own namespace. Thus, two different packages may contain classes with the same name.

We can create a package by placing a package statement at the top of every source file that defines a class belonging to the package. We may later use the classes in the package by placing an import statement at the top of the source file that needs to access the classes in the package.
 

graphics/Line.java (Path of the file is relative to the CLASSPATH environment variable.)

 package graphics;       // Class Line belongs to package graphics.

 public class Line {      // The public class modifier makes this class accessible outside the package.
     ...
}

MyTest.java

import graphics.*;     // Provides access to all public classes in package graphics.

class MyTest {
    public static void main(String[] args) {
         Line line;
         graphics.Line line2;   // Can be used for conflict resolution if two packages have a Line class.
         line = new Line(0,0,3,4);
         line2 = new Line();
    }
}
 

If a package name is not specified for a class, then the class belongs to the default package. The default package has no name and it is always imported.

Here are a few of the core Java® packages:

  • java.lang            - core Java® language.
  • java.io               - input/output streams.
  • java.util             - utility classes, e.g. Stack, Vector, Hashtable, Oberserver/Observable.
  • java.net             - networking classes.
  • java.security      - security classes.
  • javax.swing       - Swing Graphical User Interface (GUI) components (the new preferred way).
  • java.awt            - Abstract Window Toolkit GUI components (the old way).
  • java.awt.image  - image processing.

Member Access Specifiers

There are four types of member access levels: private, protected, public and package. Note that, unlike C++, we must specify access levels on a per-member basis.

class Access {
    private privateMethod();                      // Access level is "private".
    protected protectedMethod();               // Access level is "protected".
    public publicMethod();                        // Access level is "public".
    packageMethod();                               // Access level is "package".
}

 

ACCESS SPECIFIER

ACCESSIBLE BY CLASS DEFINITION

ACCESSIBLE BY SUBCLASS DEFINITION

ACCESSIBLE BY REST OF PACKAGE

ACCESSIBLE BY REST OF WORLD

private

yes

no

no

no

protected

yes

yes

yes

no

public

yes

yes

yes

yes

none i.e. package

yes

no

yes

no


 

Instance and Class members

As in C++, we can have instance members or class members. A class member is declared using the static keyword.

class MyPoint {
    int x;
    int y;
    static int x_origin;
    static int y_origin;
}

In this example, every object has its own x member, however, all objects share a single x_origin member. 


Constant Members

A final variable is one whose value cannot be changed e.g.

class Avo {
       final double AVOGADRO = 6.023e23;
}



Class Modifiers

We have already seen some examples of member modifiers, such as public and private. Java® also allows us to specify class modifiers.

  • A public class is one which can be used by objects outside the current package e.g.package graphics;       // Class Line belongs to package graphics.

public class Line {      // The public class modifier makes this class accessible outside the package.
     ...
}
 

  • An abstract class is one which cannot be instantiated, and must be subclassed instead. An abstract class may contain abstract methods i.e. methods with no implementation, however, it may also provide default implementations for other methods.  e.g.


abstract class GraphicObject {
        int x, y;
        ...
        void moveTo(int newX, int newY) {
           ...
        }
       abstract void draw();  //  This means that the class must be made abstract.
}

class Circle extends GraphicObject {
       void draw() {
            ...
       }
}
 

  • A final class is one which cannot be subclassed. This may be required for security or design reasons. e.g.


final class String {
     ...
}

It is also possible to make individual methods final.


地震让大伙知道:居安思危,才是生存之道。
posted on 2007-02-25 15:37 小寻 阅读(872) 评论(0)  编辑  收藏 所属分类: j2se/j2ee/j2me

只有注册用户登录后才能发表评论。


网站导航: