Here you will learn how to create and destroy the objects, how to create class and subclass a
classes, how to write the methods, and even how to create and use the interfaces.
A D V E R T I S E M E N T
This chapter
covers everything from how to protect an object from other objects and overriding methods, to
create template classes using the abstract classes and methods and patriarch of the Java
object hierarchy--java.lang.Object class.
Life Cycle of the Object
an object is a module that has both state and behaviour. An object's state is
contained within the member variables and the behaviour is implemented by its
methods.
The Java programs that you write will create many different objects by the
template, these templates are known as classes. The objects created interact with each
other by sending messages. As a result of messag, method is invocated which will perform
some action or it may also modify the state of object which is receiving the message. By
these interaction of the objects, your Java code can implement a graphical user interface,
run animations, or can also send and receive information over network.
Once the object completes the work it was created for, it is destroyed and all the
resources assigned to it are recycled for use, by some other objects.
Creating the Classes
A class is a template which can be used to create many objects. The class implementation
comprises of two components: class declaration and class body.
classDeclaration
{
. . .
classBody
. . .
}
Class Declaration
The class declaration, declares the name of a class along with some other
attributes like class's superclass, and whether the class is final, public,
or abstract. The class declaration should contain the class keyword and the name of the
class that you are defining. Therefore the minimum class declaration will look like this:
class NameOfClass
{
. . .
}
Class Body
Class body follows the class declaration and is always embedded within curly braces
{ and } as shown in the example above. Class body contains declarations for variables
which are members of the class, methods declarations and implemenatations of the class.
We will now discuss two special methods that you can declare within a class
body: The Constructors and finalize() Method.
Constructors
These are some of the rules on constructors:
private constructors()- keyword used "private", no one can instantiate the class as object.
But can still expose public static methods, and these methods can construct object
and return it, but no one else can do this.
package constructors() - None of them outside your package can construct an instance of your
class. This is useful when you want to have classes in your package which can do new
yourClass() and don't want to let anyone else to do this.
protected constructors() - keyword used "protected" only the subclasses of your class
can make use of this package.
public constructors() - keyword used "public" the generic constructor
will use these.
Declaring the Member Variables
An object do maintains its state by the variables defined within that class. These
variables are known as the member variables. While declaring the member variables for the class,
you can specify a host of different "attributes" about those variables: its name,
its type, access permission assigned to it, and so on.
Member variable declaration looks like this:
[accessSpecifier] [static] [final] [transient] [volatile] type variableName
The items in the square brackets are optional. The words inside the bracket are to be
replaced by names. or keywords.
Words specified inside the bracket defines the following aspects of variables:
accessSpecifier defines that which all other classes do have access to tahat variable
static indicates the variable declared is class member variable as
opposed to instance member variables.
final indicates the variable is constant.
transient variables are not part of object's persistent state.
volatile means the variable is modified asynchronously.
Writing a Method
In Java we define methods within the body of a class for which it implements the
behaviour. We usually declare methods after its variables in the class body
although not required.
Similar to the class implementation, a method implementation also consists of
two parts: method declaration and method body.
methodDeclaration
{
. . .
methodBody
. . .
}
Method Declaration
At the minimum, the method declaration component has a return
type which indicates the data type of value returned by the method, and name of the method.
returnType methodName()
{
. . .
}
Cosider for example, the following code declares a simple method named isEmpty() within
the Stack class that returns boolean value (either true or false).
class Stack
{
. . .
boolean isEmpty()
{
. . .
}
}
The method declaration shown in the example above is very basic. Methods do have many
other attributes like access control, arguments and so on. This section will cover
these topics.
The Method Body
In the method body all the action of a method takes place, the method body do
contains all legal Java instructions that implements the method. For example,
here is a Stack class with the implementation for isEmpty() method.
class Stack
{
static final int STACK_EMPTY = -1;
Object stackelements[];
int topelement = STACK_EMPTY;
. . .
boolean isEmpty()
{
if (topelement == STACK_EMPTY)
return true;
else
return false;
}
}
Within method body, you can do use "this" to refer the current object.
What is Subclasses, Superclasses, and Inheritance?
As other object-oriented programming languages in Java, one class can be derived from
other class. For example, suppose you hav a class named MouseEvent that represents
the event when user presses the mouse button in the GUI window environment. Later,
while developing application, you realize that you need a class to represent
event when user press a key on the keyboard. You can write the KeyboardEvent
class from scratch, but since MouseEvent and the KeyboardEvent classes share some states
and behaviours like which mouse button or key was pressed,the time
that the event occurred, and so on, we can go for duplicating the MouseEvent class
rather than re-inventing the wheel, You can take advantages of subclassing and
inheritance..and so you create a class Event from which both MouseEvent and
KeyboardEvent can be derive
Event is now a superclass of both MouseEvent and KeyboardEvent classes. MouseEvent and
KeyboardEvent are now called subclasses of class Event. Event do contains all the states
and behaviour which are common to both mouse events and keyboard events.
Subclasses, MouseEvent and KeyboardEvent, inherit the state and behaviour from the
superclass. Consider for example, MouseEvent and KeyboardEvent both inherits the time
stamp attribute from super class Event.
How to Create a Subclass
You do declare that a class is subclass of another class in the Class Declaration.
Suppose that you wanted to create a subclass called "ImaginaryNumber" of the
"Number class". (where the Number class is a part of java.lang package and is
base class for Floats, Integers and other numbers.).You can now write:
class ImaginaryNumber extends Number
{
. . .
}
This line declares ImaginaryNumber as a subclass of Number class
Write a Final Class
Java allows us to declare our class as final; that is, the class declared as final cannot
be subclassed. There are two reasons why one wants to do this: security
and design purpose.
Security: To subvert systems, One of the mechanism hackers do use is, create subclasses
of a class and substitute their class for the original. The subclass looks same as the
original class but it will perform vastly different things, causing damage
or getting into private information possibly. To prevent this subversion, you should
declare your class as final and prevent any of the subclasses from being created.
Design: Another reason us to declare a class as final is object-oriented design
reason. When we feel that our class is "perfect" and should not have subclasses further.
We can declare our class as final.
To specify that the class is a final class, we should use the keyword "final" before the
class keyword in the class declaration.If we want to declare the
ImaginaryNumber class as final calss, its declaration should look like this:
final class ImaginaryNumber extends Number implements Arithmetic
{
. . .
}
If subsequent attempts are made to subclass ImaginaryNumber, it will result in a
compiler error as the following:
Imagine.java:6: Can't subclass final classes: class ImaginaryNumber
class MyImaginaryNumber extends ImaginaryNumber {
^
1 error
Create a Final Method
If creating final class seems heavy for your needs, and you just want
to protect some of the classes methods being overriden, you can use final
keyword in the method declaration to indicate the compiler that the method cannot be
overridden by subclasses.
Writing Abstract Classes
Sometimes you may want only to model abstract concepts but
don't want to create an instance of the class. As discussed earlier the Number
class in java.lang package represents only the abstract concept of numbers. We can
model numbers in a program, but it will not make any sense to create a generic
number object. Instead, the Number class behaves as a superclass to
Integer and Float classes which do implements specific case of numbers.
Classes like Number, that implements only the abstract concepts and thus should not
be instantiated, are called abstract classes.
An abstract class is a class which can only be subclassed and cannot
be instantiated.
To declare the class as an abstract class we use the keyword "abstract" before
the keyword class in the class declaration:
abstract class Number
{
. . .
}
If any attempt is made to instantiate an abstract class, compiler will displays
error as shown below and refuses to compile the program:
AbstractTest.java:6: class AbstractTest is an abstract class.
It can't be instantiated.
new AbstractTest();
^
1 error
Writing the Abstract Methods
An abstract class can contain abstract methods, abstract methods are the methods,
with no implementation. Therefore an abstract class can define all its programming
interface and thus provide its subclasses the method declarations for all the methods that
are necessary to implement the programming interface. However, an abstract class can leave
implementation details of the methods to the subclasses.
You would declare an abstract class, GraphicObject, which provides the
member variables and methods which are shared by all of the subclasses.
GraphicObject can also declare abstract methods for the methods, such as draw(),
that needs to be implemented by the subclasses, but in entirely different
ways. The GraphicObject class would look like this:
abstract class GraphicObject
{
int x, y;
. . .
void moveTo(int newX, int newY)
{
. . .
}
abstract void draw();
}
An abstract class is not have an abstract method in it. But any of the class that
do have an abstract method in it or in any of the superclasses should be declared as an
abstract class. Each non-abstract subclass of GraphicObject, such as Circle and Rectangle,
shoul provide an implementation for the draw() method.
class Circle extends GraphicObject
{
void draw()
{
. . .
}
}
class Rectangle extends GraphicObject
{
void draw()
{
. . .
}
}
How to Create and Use Interfaces
Interfaces provides a mechanism to allow hierarchically unrelated classes do implement
same set of methods. An interface is the collection of method definitions
and the constant values which is free from dependency on a specific class or a class
hierarchy. Interfaces are useful for the following purpose:
declaring methods which one or more than one classes are expected to implement
revealing the object's programming interface without revealing its class
(objects like these called anonymous objects and are useful while shipping a
package of classes to the other developers)
capturing the similarities between unrelated classes without forcing the class
relationship
Create an Interface
Creating an interface is similar to that of creating a new class. An interface
definition consists of two components: interface declaration and interface body.
interfaceDeclaration
{
interfaceBody
}
The interfaceDeclaration declares various attributes about the interface such as its
name and whether it extends another interface. The interfaceBody contains the constant
and method declarations within the interface.
Use an Interface
An interface is used when the class claims to implement that interface. A class do
declares all the interfaces that are implemented in the class declaration. To declare
that the class implements one or more interfaces, make use of the keyword "implements"
followed by comma-delimited list of the interfaces implemented by the class.
Suppose that we are writing a class that implements a FIFO queue. Since the FIFO
queue class is a collection of objects (an object which contains other objects) it
doesnot make any sense to implement the Countable interface. The FIFOQueue class
would declare that it do implements the Countable interface as shown below:
class FIFOQueue implements Countable
{
. . .
}
And thereby guaranteeing that it provides implemenations for currentCount(),
incrementCount(),setCount(), and decrementCount() methods.