Java Class Fundamentals Explained
Java Class Fundamentals Explained
Module -2
Introducing Classes
The class is at the core of Java.
It is the logical construct upon which the entire Java language is built because it
defines the shape and nature of an object.
The class forms the basis for object-oriented programming in Java. Any concept you
wish to implement in a Java program must be encapsulated within a class.
Class Fundamentals
The classes created exist simply to encapsulate the main( ) method, which has been
used to demonstrate the basics of the Java syntax.
A class is that it defines a new data type. Once defined, this new type can be used to
create objects of that type.
Thus, a class is a template for an object, and an object is an instance of a class.
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables.
The code is contained within methods.
Collectively, the methods and variables defined within a class are called
members of the class.
The general rule, it is the methods that determine how a class’ data can be used.
Variables defined within a class are called instance variables because each
instance of the class (that is, each object of the class) contains its own copy of
these variables.
The general form of a class does not specify a main( ) method.
Java classes do not need to have a main( ) method.
You only specify one if that class is the starting point for your program.
A Simple Class
Here is a class called Box that defines three instance variables: width, height, and depth.
Currently, Box does not contain any methods.
class Box {
double width;
double height;
double depth;
}
It is important to remember that a class declaration only creates a template; it does not create an actual
object. Thus, the preceding code does not cause any objects of type Box to come into existence.
To actually create a Box object, you will use a statement like the following:
Box mybox = new Box(); // create a Box object called mybox
After this statement executes, mybox will refer to an instance of Box. Thus, it will have “physical” reality
Each time you create an instance of a class, you are creating an object that contains its own copy of each
instance variable defined by the class. Thus, every Box object will contain its own copies of the instance
variables width, height, and depth.
To access these variables, you will use the dot (.) operator.
The dot operator links the name of the object with the name of an instance variable.
For example, to assign the width variable of mybox the value 100, you would use the following statement:
[Link] = 100;
In general, we use the dot operator to access both the instance variables and the methods within an object.
You should call the file that contains this program [Link], because the main( ) method is in the class
called BoxDemo, not the class called Box. When you compile this program, you will find that two .class files
have been created, one for Box and one for BoxDemo. The Java compiler automatically puts each class into its
own .class file. It is not necessary for both the Box and the BoxDemo class to actually be in the same source file.
You could put each class in its own file, called [Link] and [Link], respectively.
output:
Volume is 3000.0
Each object has its own copies of the instance variables. If you have two Box objects, each has its own copy
of depth, width, and height. It is important to understand that changes to the instance variables of one
object have no effect on the instance variables of another. For example, the following program declares two
Box objects:
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
Declaring Object:
When you create a class, we are creating a new data type. Obtaining objects of a class is a two-step
process. First, you must declare a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can
do this using the new operator.
The new operator dynamically allocates (that is, allocates at run time) memory for an object and
returns a reference to it. This reference is, essentially, the address in memory of the object
allocated by new.
This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically
allocated
Declare an object of type Box:
Box mybox = new Box();
The first line declares mybox as a reference to an object of type Box. At this point, mybox does not yet refer to an
actual object. The next line allocates an object and assigns a reference to it to mybox. After the second line
executes, you can use mybox as if it were a Box object. But in reality, mybox simply holds, in essence, the memory
address of the actual Box object.
Object reference variables act differently than you might expect when an assignment
takes place. For example, what do you think the following fragment does?
b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate
any memory or copy any part of the original object. It simply makes b2 refer to the same
object as does b1. Thus, any changes made to the object through b2 will affect the object to
which b1 is referring, since they are the same object.
This situation is depicted here:
Although b1 and b2 both refer to the same object, they are not linked in any other way.
For example, a subsequent assignment to b1 will simply unhook b1 from the original
object without affecting the object or affecting b2.
For example:
type name(parameter-list) {
// body of method
}
Here, type specifies the type of data returned by the method. This can be any valid type, including
class types that you create. If the method does not return a value, its return type must be void.
The name of the method is specified by name. This can be any legal identifier other than those already
used by other items within the current scope.
The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are
essentially variables that receive the value of the arguments passed to the method when it is called.
If the method has no parameters, then the parameter list will be empty.
Methods that have a return type other than void return a value to the calling routine using
the following form of the return statement:
return value;
Adding a method to the Box class. It may have occurred to you while looking at the preceding programs that
the computation of a box’s volume was something that was best handled by the Box class rather than the
BoxDemo class. After all, since the volume of a box is dependent upon the size of the box, it makes sense to
have the Box class compute it. To do this, you must add a method to Box, as shown here:
class Box {
double width;
double height;
double depth;
class BoxDemo3 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
This program generates the following output, which is the same as the previous version.
Volume is 3000.0
Volume is 162.0
Here, [Link]();
[Link]();
The first line here invokes the volume( ) method on mybox1. That is, it calls volume( ) relative to the
mybox1 object, using the object’s name followed by the dot operator.
Returning a Value
A better way to implement volume( ) is to have it compute the volume of the box and return the result to
the caller. The following example, an improved version of the preceding program, does just that:
class Box {
double width;
double height;
double depth;
class BoxDemo4 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
The type of data returned by a method must be compatible with the return type specified by the method.
For example, if the return type of some method is boolean, you could not return an integer.
The variable receiving the value returned by a method (such as vol, in this case) must also be compatible
with the return type specified for the method.
The call to volume( ) could have been used in the println( ) statement directly, as shown here:
[Link]("Volume is" + [Link]());
In this case, when println( ) is executed, [Link]( ) will be called automatically and its value will be
passed to println( ).
While some methods don’t need parameters, most do. Parameters allow a method to be generalized. That is, a
parameterized method can operate on a variety of data and/or be used in a number of slightly different
situations. To illustrate this point, let’s use a very simple example. Here is a method that returns the square of
the number 10:
int square()
{
return 10 * 10;
}
While this method does, indeed, return the value of 10 squared, its use is very limited. However, if you modify
the method so that it takes a parameter, as shown next, then you can make square( ) much more useful.
int square(int i)
{
return i * i;
}
Now, square( ) will return the square of whatever value it is called with. That is, square( ) is now a general-
purpose method that can compute the square of any integer value, rather than just 10.
class Box {
double width;
double height;
double depth;
class BoxDemo5 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
As you can see, the setDim( ) method is used to set the dimensions of each box.
You can rework the Box example so that the dimensions of a box are automatically initialized
when an object is constructed. To do so, replace setDim( ) with a constructor.
class BoxDemo6 {
public static void main(String[] args) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Parameterized Constructors
A constructor that has parameters is known as parameterized constructor. If we want to initialize
fields of the class with our own values, then we use a parameterized constructor.
For example, the following version of Box defines a parameterized constructor that sets the dimensions of a box as
specified by those parameters. Pay special attention to how Box objects are created.
class BoxDemo7 {
public static void main(String[] args) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
Volume is 3000.0
Volume is 162.0
To better understand what this refers to, consider the following version of Box( ):
Garbage collection only occurs sporadically (if at all) during the execution of your program.
It will not occur simply because one or more objects exist that are no longer used.
A Stack Class
A stack stores data using first-in, last-out ordering. That is, a stack is like a stack of plates on a table—the
first plate put down on the table is the last plate to be used.
Stacks are controlled through two operations traditionally called push and pop.
To put an item on top of the stack, you will use push.
To take an item off the stack, you will use pop. As you will see, it is easy to encapsulate the entire stack
mechanism.
Here is a class called Stack that implements a stack for up to ten integers:
class Stack {
int[] stck = new int[10];
int tos;
// Initialize top-of-stack
Stack() {
tos = -1;
}
// Push an item onto the stack
void push(int item) {
if(tos==9)
[Link]("Stack is full.");
else
stck[++tos] = item;
}
[Link]("Stack in
mystack2:"); for(int i=0; i<10; i++)
[Link]([Link]());
}
}
Stack in
mystac
k1: 9
8
7
6
5
4
3
2
1
0
Stack in
mystack2: 19
18
17
16
15
14
13
12
11
10