Classes
A class is a collection of a fixed number of components. The components of a class are called the members of the class. The general syntax for defining a class is
modifier(s) class ClassIdentifier modifier(s)
{
classMembers
}
where modifier(s) are used to alter the behavior of the class. ClassMembers generally consist of named constants, variable declarations and/or methods. Some modifiers are public, private, and static.
- If a member of a class is a named constant, you declare it just like any other named constant.
- If a member of a class is a variable, you declare it just like any other variable.
- If a member of a class is a method, you define it just like any other method.
- If a member of a class is a method, it can (directly) access any member of the class—data members and methods. Therefore, when you write the definition of a method, you can directly access any data member of the class (without passing it as a parameter).
The word class is a reserved word in Java and it defines only a data type; no memory is allocated.
The data members of a class (also called fields) are classified into three categories: private, public and protected. If a member of a class is private, you cannot access it outside the class. If a member of a class is public, you can access it outside the class.
The (non-static) data members of a class are called instance variables.
The methods of a class are called the instance methods of the class.
Teaching Tip
|
If a class member is declared/defined without any modifiers, then that class member can be accessed from anywhere in the package.
|
Teaching Tip
|
It is good practice to make as many instance variables and methods private as is possible. This is discussed later in this chapter.
|
Constructors
In addition to the methods necessary to implement operations, every class has a special type of method called constructors. A constructor has the same name as the class, and it executes automatically when an object of that class is created. Constructors are used to guarantee that the instance variables of the class initialize to specific values.
There are two types of constructors: with parameters and without parameters. The constructor without parameters is called the default constructor.
Constructors have the following properties:
- The name of a constructor is the same as the name of the class.
- A constructor has no type.
- Constructors of a class can be overloaded.
- Any two constructors must have different signatures.
- Constructors execute automatically when class objects are instantiated. Because they have no types, they cannot be called like other methods.
- If there are multiple constructors, the constructor that executes depends on the type of values passed to the class object when the class object is instantiated.
Teaching Tip
|
If you do not include any constructor in a class, then Java automatically provides the default constructor.
|
Unified Modeling Language Class Diagrams
A class and its members can be described graphically using Unified Modeling Language (UML) notation. The top box in the UML diagram contains the name of the class. The middle box contains the data members and their data types. The last box contains the member method names, parameter list, and return types. The + (plus) sign in front of a member indicates that it is a public member; the – (minus) sign indicates that it is a private member. The # symbol before a member name indicates that it is a protected member.
Variable Declaration and Object Instantiation
Once a class is defined, you can declare reference variables of that class type. In order to allocate memory space for the variable the operator new is used as follows:
new className()
OR
new className(argument1, argument2, …, argumentN)
The first statement instantiates the object and initializes the instance variables of the object using the default constructor.
The second statement instantiates the object and initializes the instance variables using a constructor with parameters. The number of arguments and their type should match the formal parameters (in the order given) of one of the constructors. If the type of the arguments does not match the formal parameters of any constructor (in the order given), Java uses type conversion and looks for the best match.
Accessing Class Members
Once an object is created, you can access the public members of the class. The general syntax to access a data member of a class object or a class method is:
referenceVariableName.memberName
The class members that the class object can access depend on where the object is created.
- If the object is created in the definition of a method of the class, then the object can access both the public and private members.
- If the object is created elsewhere then the object can access only the public members of the class.
The dot . (period) is called the member access operator.
Built-in Operations on Classes
Most of Java’s built-in operations do not apply to classes. The built-in operation that is valid for classes is the dot operator (.). A reference variable uses the dot operator to access public members; classes can use the dot operator to access public static members.
Assignment Operator and Classes: A Precaution
In shallow copying, two or more reference variables of the same type point to the same object. In deep copying, each reference variable refers to its own object. A way to avoid shallow copying of data is to have the object being copied create a copy of itself, and then return a reference to the copy.
Teaching Tip
|
Shallow copying is a common mistake, especially by beginning Java programmers.
|
Class Scope
A reference variable has the same scope as other variables. A member of a class is local to the class. You access a public class member outside the class through the reference variable name or the class name (for static members) and the member access operator (.).
Methods and Classes
Reference variables can be passed as parameters to methods and returned as method values.
Definitions of the Constructors and Methods of the class Clock
All material covered above is further explained through a detailed example of defining the class Clock.
In general, when you write the definition of a method of a class and the method uses an object of that class, then within the definition of the method the object can access its private data members (in fact, any private member of the class.)
Definition of the class Clock
A precondition is a statement specifying the condition(s) that must be true before the function is called.
A postcondition is a statement specifying what is true after the function call is completed.
Once a class is properly defined and implemented, it can be used in a program. A program or software that uses and manipulates the objects of a class is called a client of that class.
Teaching Tip
|
In a class definition, it is a common practice to list all the instance variables, named constants, other data members, or variable declarations first, then the constructors, and then the methods.
|
Copy Constructor
The copy constructor is a special constructor that executes when an object is instantiated and initialized using an existing object. It is very useful and will be included in most of the classes.
The syntax of the heading of the copy constructor is:
public ClassName(ClassName otherObject)
Classes and the Method toString
Whenever a class is created, Java provides the method toString to the class. This method is used to convert an object to a String object. The methods print and println output the string created by the method toString.
The default definition of the method toString creates a string that is the name of the object’s class, followed by the hash code of the object.
The method toString is a public value-returning method. It does not take any parameters and returns the address of a String object.
The heading of the method toString is:
public String toString()
You can override the default definition of the method toString to convert an object to a desired string.
Static Members of a Class
The modifier static in the heading of a method specifies that the method can be invoked by using the name of the class. Similarly, if a data member of a class is declared using the modifier static, it can be accessed by using the name of the class.
In essence, public static members of a class can be accessed either by an object, that is, by using a reference variable of the class type, or using the class name and the dot operator.
static Variables (Data Members) of a Class
For each static data member of the class, Java allocates only one memory space. Static data members of a class exist even when no object of the class type is instantiated. Moreover, static variables are initialized to their default values.
Teaching Tip
|
A static method cannot use anything that depends on a calling object.
|
Finalizers
Finalizers are special types of void methods. A class can have only one finalizer, and the finalizer can have no parameters. The name of the finalizer is finalize. The method finalize automatically executes when the class object goes out of scope.
Accessor and Mutator Methods
Every class has methods that only access and do not modify the data members, called accessor methods, and methods that modify the data members, called mutator methods.
Typically, mutator methods begin with the word set and accessor methods begin with the word get.
A well-designed class uses private instance variables and mutator and accessor methods to implement the OOD principle of encapsulation.
Creating Your Own Packages
As you develop classes, you can create packages and categorize your classes. You can import your classes in the same way that you import classes from the packages provided by Java. Every Java SDK usually contains a directory where the compiled versions of the classes are stored.
To create a package and add a class to the package so that the class can be used in a program,
you do the following:
1. Define the class to be public. If the class is not public, it can be used only within the package.
2. Choose a name for the package. To organize your package, you can create subdirectories within the directory that contains the compiled code of the classes.
The next step is to compile the file using the compile command in the SDK that you are using. If you are using JDK 5.0, which contains a command-line compiler, you include the option –d to place the compiled code of the program in a specific directory.
Once the package is created, you can use the appropriate import command and reserved word package in your program to make use of the class.
If you are using an SDK to create Java programs, then you need to be familiar with the commands to compile and execute them. Typically, an SDK automatically stores the compiled code of the classes in an appropriate subdirectory.
Teaching Tip
|
When you install JDK 5.0 in the Windows (XP) environment, the system creates two main subdirectories: Java\jdk1.5.0 and Java\jre1.5.0. These two subdirectories are typically created within the directory c:\Program Files. The files necessary to compile and execute Java programs are placed in these subdirectories, along with other files.
|
Teaching Tip
|
In the Windows (XP) environment, you can set the environment variable CLASSPATH so that when you execute a Java program, the system can find the compiled code of the program. Check your operating system’s documentation to learn how to set the environment variables.
|
Teaching Tip
|
The CLASSPATH is an environment variable. In Windows, environment variables can be set through the System Properties dialog, which can be found on the Control Panel. In the System Properties dialog, select the advanced tab, and then the environment variables button.
|
Teaching Tip
|
You can add directories to the CLASSPATH as needed.
|
Teaching Tip
|
You should demonstrate setting or altering the CLASSPATH to students.
|
Multiple File Programs
If a class is to be used in only one program, or if you have divided your program so that it uses more than one class, rather than create a package, you can directly add the file(s) containing the class(es) to the program.
Most SDKs manage multiple-file programs in the form of a project. A project consists of several files, called the project files. These SDKs include a command that allows you to add several files to a project. Also, these SDKs usually have commands such as build, rebuild, or make to automatically compile all the files required.
The Reference this
Every object has access to a reference to itself. The name of this reference is the reserved word this. Java implicitly uses the reference this to refer to both the instance variables and the methods of a class. It also uses this reference to implement cascaded method calls.
Cascaded Method Calls
The reference this can be used to implement cascaded method calls. In a cascaded method call, the result returned by one method (a reference to an object) is used to immediately call another method.
Inner Classes
Classes that are defined within other classes are called inner classes. An inner class can be either a complete class definition, or an anonymous inner class definition (classes with no name). One of the main uses of inner classes is to handle events.
Abstract Data Types
An ADT is an abstraction of a commonly appearing data structure, along with a set of defined operations on the data structure. Historically, the concept of ADT in computer programming developed as a way of abstracting the common data structure and the associated operations. Along the way, ADT provided information hiding. That is, ADT hides the implementation details of the operations and the data from the users of the ADT. Users can use the operations of an ADT without knowing how the operation is implemented.
Programming Example: Candy Machine
The purpose of this program is to write a Java application program that will put an existing candy machine into operation. The candy machine sells candies, chips, gum and cookies.
The input to this program is the item selection and the cost of the item.
The output is the selected item.
The solution to this program consists of defining the class CandyMachine with the appropriate instance variables, creating the GUI and the appropriate methods to sell the items.
Key Terms
Ø Abstract data type (ADT): A data type that specifies the logical properties without the implementation details.
Ø Accessor Method: A method of a class that only accesses (that is, does not modify) the value(s) of the data member(s).
Ø Class: Collection of a fixed number of components.
Ø Constructor: Has the same name as the class, and executes automatically when an object of that class is created.
Ø Copy constructor: Executes when an object is instantiated and initialized using an existing object.
Ø Deep copy: Each reference variable refers to its own object not the same object.
Ø Default constructor: Constructor without parameters.
Ø Finalizers: Methods that automatically execute when the class object goes out of scope.
Ø Inner classes: Classes that are defined within other classes.
Ø Instance methods: The member methods of a class.
Ø Instance variables: The non-static data members of a class.
Ø Member access operator: The dot . (period) operator; access members of a class.
Ø Members: Components of a class.
Ø Mutator Method: A method of a class that modifies the value(s) of the data member(s).
Ø Postcondition: A statement specifying what is true after the function call is completed.
Ø Precondition: A statement specifying the condition(s) that must be true before the function is called.
Ø Shallow copy: two or more reference variables of the same type point to the same object.
+7 t �� ��� -align:justify;mso-layout-grid-align:none; text-autospace:none'>To overload a method name, within a class, any two definitions of the method must have different formal parameter lists.
The signature of a method consists of the method name and its formal parameter list. Two methods have different signatures if they have either different names or different formal parameter lists.
If a method is overloaded, then in a call to that method the signature, that is, the formal parameter list of the method, determines which method to execute.
Teaching Tip
|
Detailed formal descriptions of Java’s scoping and overloading rules can be found in the Java Language Specification:
|
Programming Example: Data Comparison
The input to this program is two different data files each with a course number followed by a series of scores.
The output is a file containing the course numbers, group numbers, and the course average for each group in each course.
The solution to this program consists of reading data from two different files and printing the results to an output file. It also contains the user-defined methods calculateAverage and printResult.
Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about Java Programming Secrets. For more free information about Java and Java Training visit the following sites:http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.