15 Mar 1996

Classes

The basic unit of Java programming is a class. There are no stand-alone programs, types, or variables. Everything is packaged inside some class. Normally each Java source file contains the definition of one publicly usable class, and the name of the public class is the same as the name of the file.

A class is a collection of fields. There are two types of fields: variables and methods. Variables hold data. Methods contain executable statements (and replace what other languages call programs, functions, routines or procedures).

class HighwaySpeed {

public static byte speed_limit = 55 /*MPH*/;
public static int miles_to_km(int miles) {return 1.609*miles};
public static int km_to_miles(int km) {return 0.621* km;};

};

The keyword class is followed by its name. It is a stylistic convention of Java that class names are capitalized like proper names. The fields are then defined in a block enclosed by braces. Java classes cannot be nested inside anything else, and in Java everything is inside a class.

This example has one variable field (speed_limit). It has two method fields (miles_to_km and km_to_miles). Each method has a body delimited by braces containing all the executable statements of Java programming. Normally, method bodies would be much larger, making the size of the class definition larger.

Class Scope

Classes help to organize programming into well defined, modular units. As a library of program units begins to grow, and as new program elements are obtained from the network or from vendors, problems may arise when the same variable or function name is used in different contexts. For example, the word "Float" is a built-in class in the Java language library for floating point numbers. However, in a class devoted to designing ships, "Float" may represent a desirable attribute of the final product, and in the Rose Parade, a "Float" is a big truck covered in flowers.

Variable and method fields are qualified by their class. In the statements that make up the body of any method, fields of the current class (and its parents) are simple names. In unrelated methods, a field name can only be used when preceded by the name of the class in which it is defined. Thus one would use the name HighwaySpeed.speed_limit (classname-period-fieldname) to refer to the speed_limit field of the HighwaySpeed class, while Astronomy.speed_limit might refer to the speed of light in the Astronomy class.

Public or Private?

The HighwaySpeed.speed_limit field is declared to be a byte. This will allow speeds up to 127, which seems pretty safe now. However, if there were remarkable changes in technology to make higher speeds safe and economical, then pushing the speed limit up to 130 would require redeclaring the primitive type of the field.

Programmers are always learning that their original assumptions were wrong. Variables have to be changed to allow new values, and methods have to be changed to accommodate new arguments. This may require that client programs be changed as well.

In the worst case, change one line of code and then recompile every program in the library. Languages and program development environments try to reduce the impact of a change. Java doesn't have a separate specification or header file. Everything about a class is generated from the class source file.

Following the general Object Oriented view that things are internal unless declared otherwise, Java by default limits the use of a field name to the statements that make up the body of one of the methods of the same class (or another closely related class). The variable that any program can use, and the methods that any program can call are identified by adding the keyword public to their declaration.

Documentation of the standard Java class libraries, and any other libraries that are likely to appear, will include only a description of the public classes, methods, and fields. Anything else is part of the internal implementation of the class and is subject to change without notice.

Class = User Defined Type

Pascal introduced the idea of a "strongly typed" programming language. The problem with primitive types is that they take on values limited only by the number of bytes of storage they occupy. A one byte signed integer has values from -128 to 127. Suppose, however, you want to store the day of the month. It only has valid values of 1 to 31. The primitive types don't provide a mechanism to guard against an invalid date.

The solution is to embed a numeric field variable inside a class, and not to declare the field to be public. Then other programs cannot access the field directly. You then create public methods that allow the other programs to set and test the value of the field. However, those methods enforce rules that ensure that the data is correct and consistent.

Pascal, Ada, and other strongly typed languages have simpler ways to define numeric variables with limited ranges, or enumerated values (such as Jan, Feb, Mar, ), or arrays with properly checked indexes. Classes can accomplish this, with a bit more work, but they can also solve more general problems. Because, of course, maximum number of days in a month isn't 31, at least not in Sep, Apr, Jun, Nov, and Feb.

In the context of Java, "type" and "class" are often used interchangeably. Data is either stored in a variable of one of the primitive types, or in an object defined by one of the classes.

Oh C Can you Say

There are some important shifts in language between C/C++ and Java. They have to be assaulted immediately, because if they are bypassed they will just confuse any further discussion.

A Java Class doesn't necessarily have to be Object Oriented. The C++ language adds classes to the traditional C language in order to create objects. Any program that doesn't use objects would probably be written in C. The HighwaySpeed example class has no object oriented features, but it must be contained in a class because Java offers no alternative.

In a C++ class, the program fields are called "member functions" instead of "methods". C++ still supports ordinary functions defined at file-level. Everything in Java has to be inside some class, so adding "member" would be redundant.

Other programming languages have functions, routines, and procedures, but C tries to call everything a function. The subsequent refinement of "void" functions that return no value gets around the need for what other languages call subroutines, but it strains the conventional meaning of "function" to the breaking point. Object Oriented languages use the term "method" instead, and Java has adopted this term. However, if you slip up and call something a "function", everyone will know what you are talking about.

For a C++ class to be used by other programs, the definition of the class must be available in source form so that it can be included during the compilation of the client code. Classes are, therefore, defined in separate header files (*.h). The name and argument types of member functions are declared in the header file, but the statements in the body of the function are compiled separately in an "implementation" file (*.C or *.cpp).

Java has no header files and no preprocessor. The output of the Java compiler is a *.class file, which can both be loaded for execution and imported by another source file to supply information needed to validate use of the class. The class is defined in one unit. All the program code that makes up the body of any method is included in the method field definition within the class xxx {} block. Since variable definitions are small, and method definitions are large, it is a good idea to put all of the variable fields at the front of the class followed by all of the methods, but that is just a suggestion.

C and C++ maintain separate tables for the names of classes (structs) and the names of variables. A particuarly badly written program could use HighwaySpeed as the name of a class and also as the name of a variable. This means that classes have to have a completely new set of operators. In C++, reference to the class variable would use the "::" operator as in HighwaySpeed::speed_limit. Refrence to a field of a variable would use the "." operator as in HighwaySpeed.speed_limit.

Java uses one pool of names for variables and classes. Within a block a variable can be locally defined with the same name, and therefore "hide" a variable or class with the same name in an outer block. Howver, at any time HighwaySpeed is either a class or a variable but not both. This gets rid of the need for special "::" operators. Java qualifies eveything with a simple period. To minimize conflict, it is a stylistic convention of Java that class names begin with a capital letter (as with proper names) while field names (both variables and methods) begin with a lower case letter.

The phrase "public static" will probably confuse C programmers, since C uses the term "static" to mean non-public. Java uses static to mean that a field is not part of objects; that it is just an ordinary variable or function. Objects will be described in the next section. Separately, public is used to export a name for use outside the class.

Special Cases

If a class has only variable fields (no methods) then it replaces what other languages call a structure, struct, or record.

If a class has only methods (no data) then it provides a package of related functions. The standard Java language class Math provides functions like sin, cos, sqrt. More generally, all built-in functions for any standard service (I/O, network access, database) are distributed as part of some class.

If a class contains one public method named "main", and if that method is defined with the right characteristics, then this what other languages call a main program. More generally, a Java "program" or stand-alone application is named by the class name in which the main method resides, and it is executed by supplying that class name to the Java Interpreter.

Continue Back PCLT

Copyright 1996 PC Lube and Tune -- Java H. Gilbert

This document generated by SpHyDir, another fine product of PC Lube and Tune.