What Is a Class?

In a way, Object Oriented Programming (OOP) is a misnomer, as the fundamental things we're dealing with are classes. Perhaps it should have been called “Class-based Programming”, but it's too late to change now. So what's a class, and what's an object? There are several different ways of coming at this, and we'll try a couple of them. If you are already familiar with OOP, then just skim through the chapter to pick up the Java specifics. Be sureto visit the “What Is an Object?” section, which describes an object-oriented feature handled differently in Java (reference types).

Declaring a variable

To get a good understanding of OOP, you need to understand data types in procedural (non-OOP) languages. The idea of representing real world objects by types and variables in a computer is called abstraction. Here's a quick review. You'll be familiar with the idea of declaring a variable. In many languages, a variable declaration will look something like this:

int mm = 0;

Depending on the exact rules of a language, the keyword for the type might be “int” or “integer” or something similar, and it might come before or after the variable name. In Java, a variable is declared exactly as shown here: type name first, followed by variable name. When you write a declaration like:

int mm = 0;

you are:

  • Allocating some storage, and initializing it to zero,

  • Giving it a name, mm,

  • Saying that it can only hold values that are compatible with the int type. You cannot put a string of characters into mm.

Simple types

A “type” defines the values that a variable can take, and the operations that can be done on it. When we say “mm has type int” it means that mm can only hold whole numbers, and only in a certain range (usually corresponding to the capabilities of the underlying hardware). It can be used in addition, but not in true/false logical operations. You can't suddenly pull a string of characters out of an int variable. There are ways to convert or cast between closely related types. Java is a strongly typed language, so you can only cast between related types.

Data types make software a lot more reliable. The type part of a declaration lays down what kind of values and operations are acceptable for a given variable. The compiler will cross-check every use of a variable against its type declaration, and give error messages for obvious inconsistencies. For example, if you try to divide a string by a floating point number, the compiler will recognize that as an error. The more errors you eliminate during compilation, the fewer you have to debug during execution (or shamefully, after the product has shipped).

Most languages have around ten or so built-in simple or primitive types. These are types like character, boolean, int, floating point number, and so on. Primitive types have no visible internal structure, and often correspond to types that are directly supported in hardware. It is easy to overlook the significance of what primitive types add to a programming language, because you get so much behavior implicitly just by mentioning the type name.

Be very clear on the distinction between a type and a primitive variable as shown in Table 2-1.

Table 2-1. Distinction between a type and a primitive variable

Type

Variable

  • The name (e.g. int) is shorthand for the allowable values and operations.

  • Has a name (e.g. mm) that is used to refer to the storage, to put and get a value there.

  • Does not allocate any storage.

  • Cannot hold a value.

  • Cannot take part in operations.

  • Allocates storage.

  • The storage can hold one of the acceptable values, and can only be used for the acceptable operations.

  • The type specifies the legal operations (addition, comparison, concatenation, bit shifting, etc.)

  • A variable can only take part in operations that are specified by its type.

  • The type specifies the legal values (e.g. whole numbers between minus 128 to plus 127).

  • A variable can only hold values that are specified by its type.

Composite types

Most programming languages provide a way to group several types, to define a new type. One example would be a “Timestamp” type that is made up of three fields representing hour, minute and seconds. This is called a composite type, in contrast to a primitive type. A composite type might be made up of other composite types. An example is a Photo type that may consist of an image type and a Timestamp type (itself a composite type) saying when the picture was taken.

Different programming languages give different names to composite types. Visual Basic calls them User Defined Types. C calls them structs (structures). COBOL calls them records. Fortran calls them derived types. It's just terminology. Java calls composite types reference types, and they are popularly known as classes.

There are two important things to note about reference types:

  • Creating a reference type does not allocate any storage. When you describe a reference type to the compiler, you still have not created anywhere to store a value of that type.

  • You'll probably want to define a whole set of allowable operations and legal values to be part of your new type.

Picking up on that second point, the operations for a-type-that-you-define probably won't be as simple as the arithmetic operations on numeric primitive types. For example, say you define a composite type Timestamp. It contains three fields (hh, mm, ss). You'll want a method to update those fields with the current time. You can imagine other operations on Timestamps, too: clear, set to a known time, etc. All the methods should somehow be bundled with the definition of the Timestamp type.

In language terms, data and related functions should be bundled somehow, so you can say, “This is how we represent a Timestamp type, and these are the only operations that can be done on Timestamp types.” Programming language designers call this encapsulation.

Non-OOP languages (like C, Fortran, or classic VB) support encapsulation for built-in types, but not at all for user-defined types. Some languages support “header files” that group variables, definitions of user types, and function declarations, but this is not true encapsulation. Header files do not enforce the integrity of a type: they do not prevent invalid operations (like assigning a float to an int that represents month number), nor do they provide any information hiding. Header files don't provide true encapsulation, so they are not in Java.

Organizing data and methods into larger “chunks”

OOP languages directly support bundling together types and the functions that operate on those types. The feature that allows you to describe and combine a data structure and its methods is (drumroll...) a class. A variable whose type is a class is called an object. Your programs will typically have a few classes, and many objects belonging to those classes.

Java also supports a feature for grouping related classes together in a library. A library is known as a package to a Java compiler, and it's often implemented as a directory of files. Figure 2-3 shows how Java data structures and their methods are put into classes, classes go into source files, and source files are grouped to form packages.

Figure 2-3. Java code is organized into classes, files, and packages

image

The operations on built-in types tend to be arithmetic operations like +, -, *, and /. The operations on class types are written as statements in methods in the OOP world. Unlike procedural programming where you call functions willy-nilly, in OOP all methods are defined in some class, and you invoke methods on an object of that class. Here's an example using a class from the Java run-time library. Say you have an object of class Calendar, called “now”.

Calendar now =   /*some initialization, not shown*/

Calendar has a method called get() which takes some arguments we will ignore. When we say “you invoke methods on an object”, we mean you have to (implicitly or explicitly) provide a Calendar object, and the get() or other method will operate upon that. You don't write:

get( );

You have to write

now.get( );

That is what it means to invoke a method on an object. Keep going — this will fall into place soon.

A class doesn't just group and organize; it also restricts access to the internal representation of user-defined types. This is done with keywords like “public” and “private” attached to things in the class. Those keywords specify how visible a declaration is.

How do we express “these methods and data declarations together form a class”? It is simplicity itself. You write the methods and declarations in a source file. Then at the head of the things that belong together you write:

class classname {

and at the end of the methods and data declarations forming the class, you write a matching closing brace:

}

That's all there is to it! You can precede the keyword class with a few keywords that say how widely accessibly this particular class is. At the top of the source file, you can say what package it belongs to, and/or what packages or other classes it will import. Here's a simple Timestamp type. It contains some data declarations, but no methods (yet):

class Timestamp {
        int hrs;
        int mins;
        int secs;
}

You can put these five lines into a file called Timestamp.java and compile them with the command “javac Timestamp.java”. Go ahead and try it now.

We said earlier that Timestamp needs a method to place the current time into the timestamp fields. The class Calendar mentioned previously is in a package called java.util. So the full name of the class is java.util.Calendar, and it does things with dates and times. If we declare an object of Calendar type, we can call some of its methods to extract the current hour, minute and seconds for our Timestamp.

The statements might look like this:

java.util.Calendar now = java.util.Calendar.getInstance();

hrs = now.get(java.util.Calendar.HOUR_OF_DAY);
mins = now.get(java.util.Calendar.MINUTE);
secs = now.get(java.util.Calendar.SECOND);

The first line declares the object “now” of type Calendar, from the package java.util. The dotted notation a.b.c.d is how you refer to classes within packages, and also members within classes. The next three lines are three calls to the get() method of Calendar, with three different arguments, each telling it to get a different time-related value. Those words in capitals (“MINUTES” etc) are constant values defined in class Calendar. The argument tells get() what date/time values are sought. The return values from these calls are then assigned to the variables hrs, mins, and secs respectively.

We still need to give the method a name, and say that it returns void, i.e. no return value. Here's how:

void fillTimes() {
        // the statements from above go here
         java.util.Calendar now;
         now = java.util.Calendar.getInstance();
         hrs = now.get(java.util.Calendar.HOUR_OF_DAY);
         mins = now.get(java.util.Calendar.MINUTE);
         secs = now.get(java.util.Calendar.SECOND);
}

Writing “//” makes the rest of the line a comment in Java. We'll sometimes annotate code examples using that. So putting the whole thing together, here's a complete class with data and a method from our clock program. We just defined the Timestamp type in terms of its datafields and methods. All classes are defined by their datafields and methods.

class Timestamp {
        int hrs;
        int mins;
        int secs;

        void fillTimes() {
            java.util.Calendar now;
            now = java.util.Calendar.getInstance();
            hrs = now.get(java.util.Calendar.HOUR_OF_DAY);
            mins = now.get(java.util.Calendar.MINUTE);
            secs = now.get(java.util.Calendar.SECOND);
        }
}

A data item (as opposed to a method) in a class is a field. The methods and fields together are called the members of a class (they belong to the class). This class has three fields and one method. You will call its method fillTimes() to update the current hour, minute and second. It provides a convenient interface to extract and format from the more complicated Calendar class in the Java library.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.123.126