Lesson 6


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).

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.

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.

Public and Private Classes
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 is not 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.

Java vs. C / C++ Classes
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 or 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.

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.

Everything in Java is a class.
If a class has fields that are instance variables, then they are stored inside dynamically allocated objects created by new to represent instances of the class. However, when Java documentation uses the name "Object" capitalized like a proper name, then it is referencing a special class built into the language.

The Object class is the parent of all other classes. When any new class definition omits the extends keyword, it implicitly extends the Object class. A reference variable declared to designate member of the Object class can actually point to any dynamically allocated object from any class. In Java:

     Object x;

corresponds roughly to the C/C++ language declaration:

     void * x;

That is, "x" can designate (point to ) any type of object.

There is an important difference here between C and Java. In C there is an address operation ("&") which can be used on individual variables of primitive data types. This allows a C pointer variable to designate individual fields, internal variables, and arguments. This is also remarkably unsafe and the potential source of many programming errors.

Java only allows a reference variable to point to an instance of a class dynamically allocated with the new operation. It is not possible to simply redeclare a primitive variable to be an object.

However, since there are certainly cases where one would like to create an object that is a simple int (or float, char, or whatever), the Java language supplied a set of predefined classes in the library that act as wrappers for the primitive data types.

Numeric Classes, An Example

For example, to handle simple integer values (including values from the primitive types byte, short, and int), the Java language defines the "Integer" wrapper class. Again, note that while int is a primitive and a reserved word, "Integer" is capitalized like a proper name and represents a predefined class of the Java language library.

     Integer count = new Integer(25);

In this example, the variable "count" is not an arithmetic type. It is a reference to an object from the class Integer. An Integer object is dynamically allocated and contains, essentially, one internal instance variable that contains the value (25 in this case). The Integer class provides methods to extract this value as a byte, short, or int value. However, "count" cannot be used in arithmetic expression such as "count++;" or "b=count+5;".

In addition to its use as a wrapper class, the Integer class also provided an opportunity for the Java language to define a number of additional static methods (plain old ordinary functions) that provide services generically related to integer values. For example, the function that converts strings containing the character representation of a number to an integer (what C programmers recognize as "atoi") is in Java a member of the Integer class.

A reference to an object created from the class Integer can be assigned to a reference variable of class Object and can be passed in a call to any method that takes a reference to an Object as an argument. Program logic can then use the instanceof operation to determine that it really was an Integer.

An object of type Integer is not the same as a variable of type int. The intValue method can be used to "convert" an Integer to an int, although a more precise statement would be that it extracts the value of the internal instance variable from the object.

     int k = count.intValue();

An integer literal or variable is provided to assign the Integer object its value when it is created. In the example

     Integer count = new Integer(25);

The expression "Integer(25)" is a constructor for the Integer object.

Below : a Java program that is a simple address book.

Assignment 6

- Write a Java program where you define your own (private) Java class.
Some examples include a favorite colletion (coin,stamps), or NEIU core classes needed for graduation.
- Or convert the above program to except user input for contact records.

Return to the Top