3 Objects and Classes
3 Objects and Classes
Object Variables
Object: provides a particular basis for computer applications.
Assigning Object Reference Variables:
Object reference variables act differently than you might expect when an assignment
takes place. For example, what do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
You might think that b2 is being assigned a reference to a copy of the object referred by b1. That
is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be
wrong. Instead, after this fragment executes, 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:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
Object variables:
Object variables are declared by stating the class name or data type and then the variable name
same as primitives. Objects are complex variables. They have an internal state and various
behaviors that can either change the state or simply tell something about the object.
Example:
public void objectVariables() {
Rectangle rect1;
Rectangle rect2;
// 2 Rectangle objects exist??
// more code to follow}
1
Object variables in Java are actually references to objects, not the objects themselves. object
variables store the memory address of an object of the proper type not an object of the proper type.
contrast this with primitive variables. rect1 and rect2 are variables that store the memory addresses
of Rectangle objects.
Defining a Class
Class: Describes a set of related objects.
Classes:
1. A class contains Data members and Functions.
2. Data members are accessed through the functions.
Example:
Class animal {
public int noOfLegs;
public String name;
private char gender;
public void showData()
{
display(“Name : “ +name);
display(“Number of Legs :” +noOfLegs);
display(“Gender :” +gender);
}
}
Member Function:
1. It is message to an object.
2. It is usually declared public.
3. Should not have the same name as a data member.
2
Using the class:
Instantiating a class:
Animal animl = new Animal ();
Assigning values:
animl.name = “Zebra”;
Calling a member functions:
animl.showData();
For all objects, the memory needed to store the objects, is allocated dynamically using the new
operator and a constructor call. (Strings are a special case.) constructors are similar to methods,
but they are used to initialize objects.
Using Objects:
Once an object is created and an object variable points to it then Object may be manipulated via
its methods
3
Example:
Rectangle r1 = new Rectangle();
r1.resize(100, 200);
r1.setLocation(10, 20);
int area = r1.getWidth() * r1.getHeight();
Rectangle r2 = null;
r2.resize( r1.getWidth(), r1.getHeight() * 2 );
Use the dot operator to deference an object variable and invoke one of the objects behaviors.
Available behaviors are spelled out in the class of the object, (the data type of the object)
Instance fields, Construction and Methods
Java variables are classified into three kinds of scope of variables:
1. Instance variables (Instance fields)
2. Class variables and
3. Local variables
Instance and class variables are declared inside a class . Instance variables should be called with
objects only. They take different value for each object. On the other hand class variables are global
to a class and belong to the entire set of objects that a class creates ( declared with static keyword).
Only one memory location is created for each class variable. Instance variables and class (static)
variables are accessible by whole class. That is, any method can call them and use them.
Variables declared and used inside methods are called local variables. Local variables can also be
declared inside program blocks that are defined between an opening brace “ { “ and a closing brace
“ } “.these variables are visible to the program only from the beginning of its program block to the
end of the program block. The area of the program where the variable is accessible is called its
scope.
Example:
public class VariableScope // qty and rate are instance and class variables
{ // scope is throughout the class; i.e accessible from any method
int qty=20; // and can be called without object as its static
static double rate=45.5;
public void calculate()
{
double commission=4.5; //local variable; scope is within calculate method only
System.out.println("Commission to pay:" +qty*rate*commission/100);
}
4
public static void main(String[] args)
{
VariableScope vs=new VariableScope();
double total=vs.qty*rate; // qty is called with object as it is instance variable
System.out.println("Total to Pay:" +total);
vs.calculate(); // and rate is called directly as it is static
} // total is local and can be accessed within main method only
}
Output:
Total to pay : Rs. 910.0
Commission to pay : Rs. 40.95
Constructor initializes of an automatically object is created. It has the same as the class in which
it resides and is syntactically similar to a method. The name of the constructor and the class must
be the same. Constructors do not have a return type ( at least void). Constructors can be overloaded
like methods.
Example:
class Rectangle
{
int length;
int width;
Rectangle(int a,int b)
{
length=a;
width=b;
}
int area()
{
return(length*width);
}
public static void main(String[] args)
{
Rectangle rect=new Rectangle(40,50); // calling constructor
int x=rect.area();
System.out.println("Area is:"+x);
}
}
5
Output :
Area is : 2000
Introducing Methods:
classes usually consist of two things: instance variables and methods. The topic of methods is a
large one because Java gives them so much power and flexibility.
This is the general form of a method:
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;
Here, value is the value returned. In the next few sections, you will see how to create various
types of methods, including those that take parameters and those that return values.
Adding a Method to the Box Class:
Although it is perfectly fine to create a class that contains only data, it rarely happens. Most
of the time you will use methods to access the instance variables defined by the class.
In fact, methods define the interface to most classes. This allows the class implementer
to hide the specific layout of internal data structures behind cleaner method abstractions.
In addition to defining methods that provide access to data, you can also define methods
that are used internally by the class itself.
6
Example:
This program includes a method inside the box class.
class Box
{
double width;
double height;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}}
7
Output :
Volume is 3000.0
Volume is 162.0
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. Thus, the call to
mybox1.volume( ) displays the volume of the box defined by mybox1, and the call to
mybox2.volume( ) displays the volume of the box defined by mybox2. Each time volume( ) is
invoked, it displays the volume for the specified box.
If you are unfamiliar with the concept of calling a method, the following discussion will help clear
things up. When mybox1.volume( ) is executed, the Java run-time system transfers control to the
code defined inside volume( ). After the statements inside volume( ) have executed, control is
returned to the calling routine, and execution resumes with the line of code following the call. In
the most general sense, a method is Java’s way of implementing subroutines.
There is something very important to notice inside the volume( ) method: the instance variables
width, height, and depth are referred to directly, without preceding them with an object name or
the dot operator. When a method uses an instance variable that is defined by its class, it does so
directly, without explicit reference to an object and without use of the dot operator. This is easy to
understand if you think about it. A method is always invoked relative to some object of its class.
Once this invocation has occurred, the object is known. Thus, within a method, there is no need to
specify the object a second time. This means that width, height, and depth inside volume( )
implicitly refer to the copies of those variables found in the object that invokes volume( ).
Returning a Value:
The volume of a box, 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 :
Example:
// Now, volume() returns the volume of a box.
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}}
8
class BoxDemo4
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}}
As you can see, when volume( ) is called, it is put on the right side of an assignment
statement. On the left is a variable, in this case vol, that will receive the value returned
by volume( ). Thus, after
vol = mybox1.volume();
executes, the value of mybox1.volume( ) is 3,000 and this value then is stored in vol.
There are two important things to understand about returning values:
9
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. One more point: The preceding program
can be written a bit more efficiently because there is actually no need for the vol variable. The call
to volume( ) could have been used in the println( ) statement directly, as shown here:
System.out.println("Volume is " + mybox1.volume());
In this case, when println( ) is executed, mybox1.volume( ) will be called automatically
and its value will be passed to println( ).
10