Given by Geoffrey C. Fox, Nancy McCracken at CPS606 Fall Semester 1999 on Sept 7 1999. Foils prepared Sept 6 1998
Outside Index
Summary of Material
In Part 1 of the Tutorial We Covered:
|
This Part(2) of Tutorial Covers |
Java Programming Language
|
Object Oriented and Class Structure
|
Exceptions |
And in the Remaining Parts of the Java Tutorial We Cover:
|
Outside Index Summary of Material
Part II: Java Language and |
Object-Oriented Concepts |
|
Java syntax has many similarities to C/C++.
|
But there are some differences
|
Three types of comments are supported:
|
Java reserves the following keywords:
|
null, true, and false are literals with special meaning |
Source code of a Java program consists of one or more compilation units, implemented as files with .java extension. |
Each compilation unit can contain:
|
Java compiler (called javac) reads java source and produces a set of binary bytecode files with .class extensions, one for each class declared in the source file. For example, if Foo.java implements Foo and Fred classes, then "javac Foo.java" will generate Foo.class and Fred.class files. |
Suppose that Foo implements an applet and Fred is an auxiliary class used by Foo. If Netscape/Internet Explorer encounters a tag <APPLET code="Foo.class">, it will download Foo.class and Fred.class files and it will start interpreting bytecodes in Foo.class. |
Each Java variable or expression has a definite type, given by a declaration such as
|
There are three "types" of types!
|
There are 4 integer types: byte, short, int, long of size 8, 16, 32 and 64 bits, respectively. |
float is 32 bits, double is 64 bits. Floating point arithmetic and data formats are defined by IEEE754 standard. |
characters are given by 16bit Unicode charset and represented as short integers. |
One can use casts for conversion such as
|
Note booleans are either TRUE or FALSE -- they are not 0, 1 ,-1 ... |
Arrays are "true" or "first class" objects in Java and no pointer arithmetic is supported. |
Like other objects, an array must be declared and created:
|
Arrays of arbitrary objects can be constructed,
|
An array of length 128 is subscripted by integers from 0 to 127. |
Subscripts are range checked in runtime and so vec[-1] and vec[128] will generate exceptions. |
Array length can be extracted via the length instance variable, e.g.
|
Arrays can have dynamic sizing (a fixed size determined at runtime)
|
Multidimensional arrays are arrays of arrays
|
Java's expressions are very similar to C and include the following forms. Both expressions and statements have values.
|
if (some boolean expression) { .. }
|
Nested: if (some boolean expression) { .. }
|
while (any boolean) { /* Do Stuff */ } |
do { /* What to do */ } while (another boolean); |
for (expression1; booleanexpression ; expression2) { ...}
|
switch (expression) /* Just as in C */
|
One can go to the next iteration of a loop by using
|
or break out of the loop by using
|
Subprograms in Java are called methods. The definition format is |
|
The parameter list contains the types and names of all the parameters. |
The declarations and statements are called the body of the method. Parameter names and variables declared in the body are local to it. |
Control returns from the methods either when the body is finished execution or a return statement is encountered. Return statements may also return a result. |
Programs are composed of a set of modules called classes. Each class is a template specifying a set of behaviors on the data of the class. |
Each class has class variables (sometimes called instance vars) to hold the data and methods (called functions or procedures in other languages) to define the behaviors. Each object in a program is created as an instance of a class. Each class instance has its own copy of the class variables. |
Classes can be used for data encapsulation, hiding the details of the data representation from the user of the class (by marking variables as private). |
Instance |
Variables |
Methods |
The class definition consists of
|
Each class has an API (Application Programming Interface) consisting of all the variables and methods that other programmers (i.e. in other classes) are allowed to use. These are designated by the "public" keyword. |
Example showing part of the Java Date class:
|
This declares object today to have type class
|
An example application using a method of the Date class:
|
A class (such as a "main routine") may also be implemented to have just one computational instance. |
This application reads from standard input and counts number of characters which are then printed
|
Class declaration in Java shares common aspects with C++ but there are also some syntactic and semantic differences. |
ClassModifiers class className [extends superClass] [implements interfaces] { <body of class>}
|
Only single inheritance is supported but aspects of multiple inheritance can be achieved in terms of the interface construct. Interface is similar to an abstract class with all methods being abstract and with all variables being static (independent of instance). Unlike classes, interfaces can be multiply-inherited. |
Possible ClassModifiers are:
|
threadsafe: Instance or static variables will never change asynchronously and so can use compiler optimizations such as assigning to registers. Next modifier -- final -- is also valuable to compilers |
final -- Cannot have a subclass for classes
|
MethodModifier ReturnType Name(argType1 arg1, ......) |
Returntypes are either simple types (int, byte etc.), arrays or class names |
Possible MethodModifiers are:
|
use
|
containment
|
inheritance
|
In the class definition of B, the child class, there is no need to repeat declarations of variables and methods of A, they are assumed to be there. The definition of B has the additional variables and methods of B. |
If you call a method in a class that was defined in some parent, the compiler has a simple algorithm to find the definition: it searches up the parent/child hierarchy. |
Class: |
method A |
Definition of method |
is given in parent |
Class: |
Class: |
Class: |
Class: |
Object2 |
Object1 |
Object1 creates object2 |
and calls object2.A |
This algorithm also works for the case when the method is overridden |
Class: |
method A |
Definition of method |
is given in parent |
Class: |
Class: |
method A |
Class: |
Class: |
Object2 |
Object1 |
Object1 creates object2 |
and calls object2.A |
Casting (type conversion) is supported between types and class types. Syntax:
|
Two forms of casting are possible: widening and narrowing |
Widening, where the subclass is used as an instance of the superclass, is performed implicitly |
Narrowing, where the superclass is used as an instance of the subclass, must be performed explicitly |
Given Parent: Dot -> DrawableDot (Child):
|
Casting between sibling classes is a compile-time error |
Not in any package |
One final instance variable: length |
For each primitive type (and all classes), there's an implicit Array subclass |
Cannot be extended (subclassed) |
Superclass is Object |
Inherits methods from Object
|
Many languages are confusing as they differ in often unstated distinction between the value and "handle" -- Java is no exception! (reference,address,pointer) of an entity |
Consider assignment: a = b; // sets value of a to value of b |
If a and b are primitive types, then they hold "actual literals" and so if b=66, then a is set to 66
|
However if a or b is an object, b is in fact a reference and so one sets a to refer to same object as b (i.e. same "location" in memory)
|
Arguments to Methods are always passed by value BUT if an object is an argument, then that value is ALWAYS a reference and so in practice
|
Arrays reflect properties of what they are arrays of! |
Overriding Methods (where child class provides method with same signature as method in parent)
|
Overloading (where a class can provide a set of methods all with the same name, but with different signatures): The signature is defined (as in Arnold-Gosling book) by
|
An abstract method has no body - it is provided in a class to define the signature of the method for program structuring purposes. It must be defined in some subclass of the class in which it is declared.
|
Classes that contain abstract methods and classes that inherit abstract methods without overriding them are considered abstract classes
|
An interface specifies a collection of methods (behaviors) without implementing their bodies (akin to giving the API).
|
Any other class which implements the interface is guaranteeing that it will have the set of behaviors, and will give concrete bodies to the methods of the interface. |
Interfaces solve some of the same problems as multiple inheritance, without as much overhead at runtime.
|
Interfaces can be implemented by classes on unrelated inheritance trees, making it unnecessary to add methods to common superclass. |
A class may implement an interface, in which case it provides the body for the methods specified in the interface. |
interface storable has store and retrieve methods
|
Interfaces behave exactly as classes when used as a type. |
The normal type declaration syntax "interfaceName variableName" declares a variable or parameter to be an instance of some class that implements interfaceName.
|
Interfaces are either public or have the default friendly access (public for the package and private elsewhere) |
Methods in an interface are always abstract and have the same access as the interface. No other modifiers may be applied |
Variables in an interface are public, static, and final. They must be initialized. |
Interfaces can incorporate one or more other interfaces, using the extends keyword:
|
A class can implement more than one interface:
|
Note that Interfaces often play a software engineering as opposed to required functional role |
Note that Interfaces are not significantly used in current Java release where perhaps there are 15 times as many class definitions as interface definitions |
But Interfaces play a crucial role in the Remote Method Interface (RMI), where an Interface is the common specification between a Java applet or application and the set of methods that it can call remotely. |
One file can contain several related classes, but only one of them can be public. If the public class is called wheat.java, then the file must be called wheat. |
A set of classes in different files can be grouped together in a package. Each of the files must be in the same directory and contain the command
|
The name of the directory must also be mill. |
Directory name: mill |
File: wheat.java: stone.java: |
package mill package mill |
public class wheat . . . public class stone . . . |
One conveniently uses files in a package by inserting
|
at the beginning of a file that needs classes from the mill package
|
Packages can be grouped hierarchically, with the corresponding directory tree. For example, the mill package could be a subpackage of agriculture. Then a class is referred to as agriculture.mill.Classname. |
Except for classes provided with the Java language, all of which have the form java.X, a class that is imported or used must either be in the current directory or be accessible to the compiler through the CLASSPATH environment variable. |
java.lang Contains essential Java classes and is by default imported into every Java file and so import java.lang.* is unnecessary. Thread, Math, Object and Type Wrappers are here |
java.io contains classes to do I/O. This is not necessary (or even allowed!) for applets which can't do much I/O in Netscape! |
java.util contains various utility classes that didn't make it to java.lang. Date is here as are hashtables |
java.net contains classes to do network applications. This will be important for any distributed applications |
java.applet has the classes needed to support applets |
java.awt has the classes to support windowing -- The Abstract Windows Toolkit |
java.awt.image has image processing classes
|
java.awt.datatransfer Classes and interfaces to transfer data from a Java program to the system clipboard (enabling drag-and-drop) |
java.beans Contains classes to write reusable software components |
java.lang.reflect Enables a program to discover the accessible variables and methods of a class at run-time |
java.rmi Remote Method Invocation |
java.security Enables a Java program to encrypt data and control the access privileges provided |
java.sql Java Database Connectivity (JDBC) enables Java programs to interact with a database using the SQL language |
java.text Classes that provide internationalization capabilities for numbers, dates, characters and strings |
java.util.zip Combines java .class files and other files into one compressed file called a Java archive (JAR) file. |
The language itself supports concept of an exception |
Java supports a hierarchical model of exceptions which allow and indeed require user to supply suitable handlers for any exception that can occur in a Java program |
Note exceptions that can occur in a method must either be caught (i.e. handled inside method) or thrown (i.e. returned to callee) |
Thrown exceptions are like returned arguments and are for instance part of interface to a method |
Exceptions are all (at some level in hierarchy) subclasses of Throwable class |
Exception class has two constructors, one of which allows a message to be included in each instance. |
The user can either throw an exception of type Exception with a unique message, or create own subclass of Exception:
|
Methods which call "MyMethod" should use a try and catch block which catches an exception e of type MyException. Methods e.getMessage and e.printStackTrace can be used on Exceptions. |
|
As Examples of hierarchy: |
catch(FileNotFoundException e) { .. } would catch particular exception whereas |
catch(IOException e) { .. } would catch all IOexceptions |
Throwable |
. . . |
Error |
Exception |
RuntimeException |
IOException |
EOFException |
FileNotFoundException |
InterruptedIOException |
File file; /* defines file to be object of class File */
|
There are two subclasses of Throwable
|
Exception has a subclass RuntimeException that need NOT be caught
|
Note that exceptions which are thrown but not caught appear as error message on stderr. For applets this is in the "Java console" of the browser. |