Given by Nancy McCracken at CPS616 spring 1997 on Jan 27 1997. Foils prepared 1 February 97
Abstract * Foil Index for this file
Secs 41.7
See also color IMAGE
Basic Object Structure of Java with general words for those unfamiliar with concept |
Classes and Methods |
Interfaces done briefly |
Packages |
Exceptions done quickly |
This table of Contents
Abstract
Instructor: Nancy McCracken |
teamed with Meryem Ispirli, Geoffrey Fox, |
Tom Scavo, John Yip |
Syracuse University |
111 College Place |
Syracuse |
New York 13244-4100 |
Basic Object Structure of Java with general words for those unfamiliar with concept |
Classes and Methods |
Interfaces done briefly |
Packages |
Exceptions done quickly |
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) 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. |
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:
|
The on-line Java Hierarchy and Index shows the API's of all Java classes. |
This declares object today to have type class
|
Date() is Constructor of Date class which constructs an instance of Date class and sets default value to be the current date
|
An example application using a method of the Date class:
|
A class may also be used to have just one computational instance. |
This application reads from standard input and counts number of characters which are then printed |
class Count { |
public static void main (String args[]) |
throws java.io.IOException |
{ int count = 0;
|
}} |
Class declaration in Java shares common aspects with C++ but there are also some syntactic and semantic differences. |
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 (global). Unlike classes, interfaces can be multiply-inherited. |
ClassModifiers class className [extends superClass] [implements interfaces] { |
e.g. public class Test extends Applet implements Runnable { |
defines an applet that can use threads which have methods defined by Runnable interface |
Methods of identical name to class are special -- they are constructors |
mPoint() { /* Default Constructor */
|
} |
We can overload method to define different versions with different numbers and types of arguments |
mPoint(int _x, int _y) { /* Constructor to set Specific Initial values */
|
} |
mPoint can have other methods to set its instance variables such as: |
public void setDelta(int _dx, int _dy) {
|
} |
Possible ClassModifiers are: |
abstract -- Contains abstract methods without implementation -- typically such abstract classes have several subclasses that define implementation of methods |
public -- May be used by code outside the class package and (unix) file must be called ClassName.java where ClassName is unique public class in file |
private -- this class can only be used within current file -- i.e current class |
friendly(i.e. empty ClassModifier) -- class can be used only within current package |
protected -- Only accessible to subclasses |
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
|
transient -- specifies that objects are not persistent |
Note most of these modifiers can be used either for a class or an object -- a particular instance of a class
|
MethodModifier ReturnType Name(argType1 arg1, ......) |
Returntypes are either simple types (int, byte etc.), arrays or class names |
Possible MethodModifiers are:
|
use
|
containment
|
inheritance
|
Call to method in Object2 (message) from object1 is passed up the class hierarchy until a definition is found |
Call to method in Object2 (message) from object1 is passed up the class hierarchy until a definition is found |
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 |
(new int[5]).getClass().getSuperclass() |
will return Java.lang.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! |
We define a parent class for movable point objects. Each instance of this class is represented by an x,y location, by a dx,dy offset for the object to move, and a color for the object. This example also illustrates data encapsulation, where users of the class must use methods to get data of the class. |
We include methods to change the default values for the offsets and color, a method to move the object, and one to paint a point. |
We define a class for movable rectangle objects. It uses x,y from the parent class mPoint for the location of the rectangle, but adds h,w to specify height and width of the rectangle. |
This applet creates 2 mRectangles and loops to move them. |
The repaint method calls update, which is overridden here to move the objects, and paint, which is overridden here to redraw whole graphics area. |
You are allowed to have more than one constructor in a class, if the constructors have different types or numbers of arguments. For example, for people who are using the java.awt.Point class, you can add a constructor to mRectangle which creates a rectangle by giving the top left and bottom right corner points. |
Once we have structured the concepts of our data into classes, it is easy to add new shapes of movable objects as child classes of mRectangle. These classes only have to redefine paint to draw a differently shaped object. |
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. |
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. |
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.peer is a secret set of classes with platform dependent details |
method1 {
|
} |
method2 throws Exception3 {
|
} |
method3 throws Exception3 {
|
} |
As Examples of hierarchy: |
catch(InvalidIndexException e) {..} would catch particular exception whereas |
catch(ArrayException e) {..} would catch all Arrayexceptions |