Ads 468x60px

Monday, July 25, 2011

Using Classes, Objects, and Interfaces

Using Classes, Objects, and Interfaces

Every Java application is essentially a class that contains the main() method. This section discusses briefly how to create and use classes, objects, and interfaces in Java applications. You'll learn about many additional elements of the Java programming language that are important to know when using classes and objects.

Creating Classes

The first step in creating an object in your application is to create its class. The following form is used to define a class:
class classname [extends classname] [implements interface] {
     [variable declaration;]
     [method declaration;]
In this form, the classname is the name of the new class; extends classname is where the parent class of a subclass would be named, after the word extends. The implements interface defines an interface used by the class (interfaces are covered later in the chapter). If you do not want the compiler to allow your class to be subclassed, you can precede your class statement with the word final. If you wish to create a class that must be subclassed, you would precede the class with the word abstract.
You explored variable declaration in detail in the first section. Keep in mind that variables must be initialized before being used in methods. Now you'll learn how methods are declared. Methods generally use the following form:
[Modifiers] return-type method-name (parameter-list) {
The return type specifies the type of data or class that is returned when the method is run. The void return type is used when no value is returned. When naming the method, you must follow the same rules for naming classes and variables described earlier in the chapter. You must always enclose the parameter list in parentheses even if the parentheses are empty. The parameter list contains the types and variable names of all variables that you want to pass to the method. The statements are the code of your method.

Overloaded Methods

You use overloaded methods in your code when you need to call a method with different sets of parameter lists. Methods that allow flexibility in the parameters they use can be called from different parts of your program with different variables. Java's API classes, discussed in Chapter 3, use overloaded methods. To allow a different type of parameter information to be passed to your method, repeat the method in your code with the alternate parameter list included, as follows:
returnvalue methodname (parameter list 1)
returnvalue methodname (parameter list 2)
When the method is called and parameters are passed to it, Java determines which version of the method has a parameter list that most closely matches the parameters passed and executes it.

Static Methods and Variables

Static methods and variables are similar to the methods and variables already discussed, but they are a part of the class and do not require you to create an object to use them. Static variables are common to all instances created from the class they are stored in. When the value of a static variable in a class is changed, it is likewise changed for all instances of the class.
You might want to use static methods to provide utilities for the rest of your application. Statics can also be used with initializers to create constant data that is used by all instances of the class. All static statements-whether they are variables, methods, or initializers-are preceded by the word static.


Constructors are methods that you use when you create objects. They take the function of initializers a step further. They have the same name as the class and return no value. A default constructor is automatically created by the Java compiler if you don't specify one in your code. It is called when an object is created without parameters. Constructors, like methods, can be overloaded.

Creating Objects

After you have a class that has variables and methods stored, you can create objects from it. You can think of an object as an area of memory that is allocated for an object's instance variables. To create the object and automatically allocate memory for it, always use the operator new. This new operator creates the object of the type specified and calls the constructor that is appropriate for the parameters passed in the parameter list. A reference is then made by Java to the new object. The form of an object creation is generally as follows:
classname reference-variable;
reference-variable = new classname (parameter-list)
The first line declares a variable that holds the reference to the object (references are explained in the next section). The second line creates a new object and assigns the variable to it. If parameters are passed, the appropriate constructor is called. If no parameters are passed, the object's default constructor is called.


References, which are created when objects are created, can be used to access variables and methods in other objects. References are used by other methods from other objects in the following form:
Variables and methods stored in other objects are called by using the reference variable followed by a dot and the name of the foreign variable or method.
You use the reference value in comparisons. The operators used in references are ==, !=, and instanceof. The == and != operators can be used to tell whether two references refer to the same object or whether a reference does not refer to any object (such a case would return a null value). The instanceof operator is used to determine whether an object was created from a certain class or one of its subclasses. If a statement comparing an object to a class using instanceof returns true, that object is in fact an instance of the specified class.
If you are a C programmer, note that pointers are replaced by references in Java. This is explained in greater detail later in the book.

Class Inheritance

When a subclass is defined, it must indicate the superclass it is being created from. This is done with the extends modifier. The form of a subclass declaration is this:
class subclassname extends superclassname {
     //new instructions
If a subclass uses a method from a superclass but adds functionality to it, it overrides the method. In Java, you do not need to duplicate the code in the other class. Just refer to the original method in the superclass with super.

null, this, and super Variables

Every class has the following three special variables: null, this, and super.
The null variable has a reference that points to nothing. You may use this reference to assign no value to a variable's identifier. null variables are empty containers that represent the absence of an object. To create an empty container, the following form is used:
datatype variablename = null;
The this variable has a reference to the actual object. A class can refer to itself using this. To refer to itself, a class uses the following form:
The super variable has a reference to the superclass type of the class. You might wish to reference the superclass type when creating objects. Just precede your variables with the word super:
super (x,y)


Encapsulation is used to hide methods and variables in your classes from being accessed from foreign methods. To encapsulate variables and methods in your classes, precede their declarations with the keyword private. Private variables and methods can be seen only within a class. Subclasses or external methods cannot see them.

Access Modifiers

The private modifier is one of three types of access modifiers that control the way foreign methods see your variables, methods, and classes. The others are public and protected.
Any foreign methods are able to access variables and methods preceded by the word public. There can be only one public class per source file. This class must have the same name as the source file. Applets, which are explained in detail in a later chapter, must contain at least one public class that is a subclass of the Java.Applet package.
Protected variables and methods can be used only within a class or its subclasses. Foreign methods cannot access protected variables and methods.

Creating Interfaces

Interfaces in Java are unlike interfaces in any other language. They provide a second form of inheritance. Because Java does not allow you to inherit from more than one superclass, Java lets you implement interfaces, which provides you with the functionality that inheritance from multiple superclasses would. Using interfaces, your object can use methods and variables from classes that are outside of its class hierarchy.
Interfaces are structured as entirely abstract classes with variables that are static and final and contain methods without code to implement them. Interfaces can inherit from an unlimited number of other interfaces. They are structured the same way in which classes are structured, except with the keyword interface instead of class:
interface interfacename [extends interfacename] {
     [variable declaration;]
     [method declaration;]
Interfaces are implemented by classes and can extend other interfaces. Classes that implement interfaces include the code for the methods of interfaces. These classes can implement more than one interface.
Interfaces can be used to conjoin several unrelated classes and have them respond to the same methods. For example, using interfaces, several shape classes such as rectangle, triangle, and circle can respond to a method called MoveLeft(), which would repaint the shape a certain distance to the left of the original location. In such a case, MoveLeft() would be declared in the interface, but its code would be stored in the class that implements the interface.


Java provides you with several libraries of classes which are called packages. You can use any of the classes in these packages by importing them into your application. Additionally, you may wish to package related classes you create so they can be reused in other applications. Packages are presented in detail in 


Post a Comment