Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter Three - Objects and Classes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

CHAPTER THREE

OBJECTS AND CLASSES

Objectives
After studying this lesson you should be able to
• Declare classes, access them for various purposes.

• Explain how methods are useful and how method accept parameters.

• Explain various concepts like method definition, passing arguments, return and method call.

• Explain an important concept known as constructor.

• Explain Overloading method and overloading constructor.

3.1 Class Fundamentals


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. As such, 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.
Perhaps the most important thing to understand about 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. Because an object is an instance of a class, you will often
see the two words, object and instance, used interchangeably.

The General Form of a class


The basic element of object – oriented programming is a class. A class defines the shape and
behavior of an object and is a template for multiple objects with similar features. Any concept
represented in a program is encapsulated in a class. When an application is written, classes of objects
are defined. To create a class, a source file with the class keyword in it followed by a legal identifier
and a pair of curly braces for the body is required. The general form of a class definition is shown here:

class classname {
type instance-variable1;
type instance –variable2;
// …
type instance-variableN;
type methodname ( Parameter-list )
{
// body of the method
}
}

1
The data or variables, defined with in 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. In most classes, the instance variables are acted upon and accessed by the methods defined
for that class. Thus, it is methods that determine how a class data can be used.
Variable 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. Thus, the data for one object
is separate and unique from the data for another object.
For example, a class called Book includes all its features serving as template for the concept.
Each property is treated as an attribute of that class. For example, the book’s name, the author’s name,
number of pages it contains are its attributes. The definition of the Book class would be:

class Book {
String name;
String authorname;
int nopages;
}
Apart from defining an object’s structure, a class also defines its functional interface, known as
methods. The Book can have a method that displays the name of the book:
class Book{
String name;
String authorname;
int nopages;
String displayName() {
System.out.println(“ Name of the book is “+ name );
}
}
Once a Book class is defined, instance of that class can be created and each instance can have
different attributes. When the program runs, instances of the class are created and discarded as and
when required.

Instantiation and Initializing Class Objects


An instance of a class can be used to access the variables and methods that form part of the
class. Each instance of the class has its own copy of instance variables defined in the class and hence
can hold different attributes. For instance, one object of the Book class can contain the attributes of
‘Gone with the wind’ while other may contain that of ‘Learn Java’.

The methods in the class operate on individual instance of the class. For example, the same
display method can operate on both the instances of the book class described above.
Obj1.displayName() displays the attribute of the obj1, while obj2.displayName()
displays that of obj2.

The following example explain the creation of a class. Here is a class called Box that defines
three instance variables: width, height and depth. Currently, Box does not contain any methods.

2
class Box {
double width ;
double height ;
double depth;
}
As stated, a class defines a new type of data. In this case, the new data type is called Box. You
will use this name to declare objects of type Box. 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
object 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 the statement executes, mybox will be an instance of Box. Thus, it will have “physical”
reality. For the moment, don’t worry about the details of this statement.
Again, 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 called member selection 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:

mybox.width = 100;
This statement tells the compiler to assign the copy of width that is contained within the mybox
object the value of 100. In general, you use the dot operator to access both the instance variables and
the methods within an object. Here is a complete program that uses the Box class:

// A program that uses the Box class


class Box {
double width ;
double height;
double depth;
}
// This class declare an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// Assign values to mybox’s instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// Compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println( “ Volume is “ + vol );
}
}

3
You should call the file containing this program BoxDemo.java, 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 Box.java and BoxDemo.java respectively.

To run this program, you must execute BoxDemo.class. When you do, you will see the
following output:

Volume is 3000.0

Declaring Objects
As just explained, when you create a class, you are creating a new data type. You can use this
type to declare objects of that type. However, 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 a 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, more or less, 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.
In the preceding sample program, a line similar to the following is used to declare an object of
type Box:
Box mybox = new Box();

This statement combines the two steps just declared. It can be rewritten like this to show each
step more clearly:
Box mybox; // declare reference to object
mybox = new Box() // allocate a Box object

The first line declares mybox as a reference to an object of type Box. After this line executes,
mybox contains the value null, which indicates that it does not yet point to an actual object.

Assigning Object Reference Variables


Object reference variables act differently than you might expect when an assignment take 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 to by b1.
That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be

4
wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. The
assignment of b1 and 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.

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 of 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.

3.2 Methods
Methods are functions that operate on instances of classes in which they are defined. Objects
can communicate with each other using methods and can call methods in other classes. Just as there are
class and instance variables, there are class and instance methods. Instance methods apply and operate
on an instance of the class while class methods operate on the class.

Defining Methods
Method definition has four parts. They are, name of the method, type of object or primitive type
the method returns, a list of parameters and body of the method. Java permits different methods to have
the same name as long as the argument list is different. This is called method overloading. A basic
method definition resembles the one given below:
return-type methodname(type1 arg1, type2 arg2){
// Body of the methods
}
The return-type is the primitive type or class of the value this method returns. It should be
void if the method does not return a value at all.

The method’s parameter list is a set of variable declarations. The list is separated by commas
within the parentheses. The parameters become local variables in the body of the method whose values
are passed when the method is called.
Inside the body of the method, statements, expressions and method-calls can be present. If the
method has a return-type, then a value must be returned using the keyword return.

Calling Methods
Calling method is similar to calling or referring to an instance variable. The methods are
accessed using the dot (.) notation. The object whose method is called is on the left of the dot, while the

5
name of the method and its arguments are on the right.
obj.methodname(param1, param2)

The following example indicates the usage of methods


class Area {
int len = 10;
int bre = 10;
void calc(){
int area = len * bre;
System.out.println(“The area is “+area+“ sq.cms“);
}
public static void main(String args[]){
Area a = new Area();
a.calc();
}
}
The output appear on the screen as given below:
The area is 100 sq.cms

The class Area has two instance variables, len and bre, which are initialized when an object is
created. The calc method, which does not return any value, is defined in line 4. This method calculates
the area and displays it. In the main method, an instance of the class, Area is created. The calc method
of the class, which calculates and displays the area, is called in line 10.

Class Methods
Class methods, like class variables, are available to instance of the class and can be made
available to other classes. Class methods can be used anywhere regardless of whether an instance of the
class exists or not. Methods that operate on a particular object should be defined as instance methods.
Methods that provide some general utility but do not directly affect an instance of the class are declared
as class methods. Class method is defined as given below:
static return-type methodname( type1 arg1, type2 arg2, ...)
{
// Body of the method
}
The static keyword indicates that it is a class method and can be accessed without creating an
object. The class methods, unlike instance method, are not allowed to use instance variables, as these
methods do not operate on an object.

Passing Argument to Methods


The objects that are passed to the body of the method are passed by reference and the basic
types are passed by value. This results in the change in original value of the object if the value is
modified in the method.
The following example depicts the passing of arguments to methods.

6
class Square {
void calc(int x){
int square = x * x ;
System.out.println(“The square of “+x+“ is “+square);
}
public static void main(String []args ){
Square a = new Square();
a.calc(15);
}
}
The output appears as shown :
The square of 15 is 225.

The calc method, which takes an integer as argument is defined in line 2. This method
calculates the square of the parameter passed and display it. In the main() method an object of this
class is created. Then, calc method is invoked with an argument 15. The calc method calculates the
square of the argument passed and displays it.

Returning a Value
While the implementation of volume() does move the computation of a box’s volume inside
the Box class where it belongs, it is not the best way to do it. For example, what if another part of your
program wanted to know the volume of a box, but not display its 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:
// 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 ;
}
}
class BoxDemo {
public static void main ( String [ ]args ) {
Box mybox = new Box();
double vol;
// Assign values to mybox’s instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// get volume of box
vol = mybox.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().

7
Overloading Methods
In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. When this is the case, the methods are said
to be overloaded, and the process is referred to as method overloading.
Method Overloading is one of the ways that Java implements polymorphism. If you have never
used a language that allows the overloading of methods, then the concept may seem strange at first. But
as you will see, method overloading is one of Java’s most exciting and useful features.
When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call. While overloaded methods
may have different return types, the return type alone is insufficient to distinguish two versions of a
method. When Java encounters a call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.
Here is a simple example that illustrates method overloading:
// Demonstrate method Overloading
class Overload {
void test ()
{
System.out.priintln ( “ No Parameters “);
}
// Overload test for one integer parameter.
void test ( int a )
{
System.out.println ( “ a : “ + a);
}
// Overload test for two integer parameters.
void test ( int a, int b)
{
System.out.println ( “ a and b : “ +a + “ “ + b);
}
// Overload test for a double parameter
double test ( double a )
{
System.out.println ( “ double a : “ + a);
return a*a;
}
}
class OverloadDemo {
public static void main ( String args[]) {
Overload ob = new Overload() ;
double result ;
// call all versions of test ()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println(“Result of ob.test(123.2): “+result);
}
}

8
This program generates the following output:
No parameters
a : 10
a and b : 10 20
double a : 123.2
Result of ob.test(123.2) : 15178.24
As you can see, test() is overloaded four times. The first version takes no parameters, the
second takes one integer parameter, the third takes two integer parameters, and the fourth takes one
double parameter. The fact that the fourth version of test() also returns a value is of no consequence
relative to overloading, since return types do not play a role in overload resolution.

3.3 Constructors
A constructor method is a special kind of method that determines how an object is initialized
when created. They have the same name as the class and do not have any return type.
When the keyword new is used to create an instance of a class, Java allocates memory for the
object, initializes the instance variables and calls the constructor methods. Constructors can also be
overloaded.
The following describes constructor definition, passing of arguments and changing of values:
class Cons {
int i;
int j;
Cons (int a , int b)
{
i = a;
j = b;
}
void print ()
{
System.out.println(“The addition of “+i+“ and “+ j
+ “ gives “ + ( i + j ) );
}
public static void main ( String args[] )
{
Cons c;
c = new Cons(10, 10);
c.print();
System.out.println(“ “);
c = new Cons(50, 50);
c.print();
}
}
The output appears as given below:
The addition of 10 and 10 gives 20
The addition of 50 and 50 gives 100
The constructor passes arguments as is declared in line 4. It also indicates the print method used
to display the values of the constructor arguments.

9
Overloading Constructors
Constructors can also take varying numbers and types of parameters. This enables creation of
objects with the properties required. The following example illustrates overloaded constructors. The
constructor takes a different number of arguments each time and gives the same to the print method for
display.
class Cload {
String pname;
int qty;
int price;
Cload(int prodqty, String prodname, int prodprice )
{
pname = prodname;
qty = prodqty;
price = prodprice;
}
Cload(int q, String p1name)
{
pname = p1name;
price = q;
qty = price / 10 ;
}
Cload(String ppname, int pprice)
{
pname = ppname;
price = (int)(pprice – (0.1));
}
void print()
{
System.out.println ( “ Product Name :“ + pname );
System.out.println ( “ Quantity :”+ qty );
System.out.println ( “ Price : “ +price );
}
public static void main ( String args[] )
{
Cload prods = new Cload (10, “ Apples” , 10 );
prods.print();
prods = new Cload (10, “ Oranges );
prods.print();
prods = new Cload (“ Grapes” , 25 );
prods.print();
}
}
The output appears as given below:
Product Name : Apples
Quantity : 10
Price : 10
Product Name : Oranges
Quantity : 1
Price : 10
Product Name : Grapes
Quantity : 0
Price : 24

10
3.4 Access Control
Access control is controlling visibility of a variable or method. When a method or variable is
visible to another class, its methods can references the method or variable. There are four levels of
visibility that are used. Each level is more restrictive than the other and provides more protection than
the one preceding it.

public
Any method or variable is visible to the class in which it is defined. If the method or variable
must be visible to all classes, then it must be declared as public. A variable or method with public
access has the widest possible visibility. Any class can use it.

package
Package is indicated by the lack of any access modifier in a declaration. It has an increased
protection and narrowed visibility and is the default protection when none has been specified.

protected
This specifier is a relationship between a class and its present and future subclasses. The
subclasses are closer to the parent class than any other class. This level gives more protection and
narrows visibility.

private
It is narrowly visible and the highest level of protection that can possibly be obtained. Private
methods and variables cannot be seen by any class other than the one in which they are defined. They
are extremely restrictive but are most commonly used. Any representation unique to the
implementation is declared private. An object’s primary job is to encapsulate its data and limit
manipulation. This is achieved by declaring data as private.

The following example depicts declaration of data as private:


class Priv {
private int x = 10 ;
void var()
{
System.out.println(“The private value is “+ x );
}
public static void main ( String args[] ){
Priv p1 = new Priv();
p1.var();
}
}
The output appears as given below :
The private value is 10

The class Priv has a private instance variable x. This variable can be accessed only inside the

11
class. The method var displays this variable using the println method. The main method creates an
instance of the class and invokes the var method. It is important to note that the instance variable x of
the object cannot be accessed directly from the main since it is declared private.

3.5 Static Methods and Final variables

Static Methods
There will be times when you will want to define a class member that will be used
independently of any object of that class. Normally a class member must be accessed only in
conjunction with an object of its class. However, it is possible to create a member that can be used by
itself, without reference to a specific instance. To create such a member, precede its declaration with the
keyword static. When a member is declared static, it can be accessed before any objects of its
class are created, and without reference to any object you can declare both methods and variables to be
static. The most common example of a static member is main(). main() is declared as static
because it must be called before any objects exist.
Instance variables declared as static are, essentially, global variables. When objects of its
class are declared, no copy of a static variable is made. Instead, all instances of the class share the same
static variable.
Methods declared as static have several restrictions:

• They can only call other static methods.


• They must only access static data.
• They cannot refer to this or super in any way.
If you need to do computation in order to initialize your static variables, you can declare a
static block which gets executed exactly once, when the class id first loaded. The following example
shows a class that has a static method, some static variables, and a static initialization block:
// Demonstrate static variables, methods and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth( int x ) {
System.out.println ( “ x = “ + x );
System.out.println ( “ a = “ + a );
System.out.println ( “ b = “ + b );
}
static {
System.out.println(“Static block initialized.“);
b = a * 4 ;
}
public static void main ( String args[] ) {
meth(42);
}
}
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to

12
3, then the static block executes and finally, b is initialized to a*4 to 12. Then main()is called,
which calls meth(), passing 42 to x. The three println() statements refer to the two static
variables a and b, as well as to the local variable x.

Here is the output of the program:


Static block Initialized
x = 42
a = 3
b = 12

Introducing final
A variable can be declared as final. Doing so prevents its contents from being modified. This
means that you initialize a final variable when it is declared (in this usage, final is similar to const
in C / C++). For example
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
Subsequent parts of your program can now use FILE_OPEN, etc., as if they were constants,
without fear that a value has been changed.
It is a common coding convention to choose all uppercase identifiers for final variables.
Variables declared as final do not occupy memory on a per-instance basis. Thus, a final variable is
essentially a constant.
The keyword final can also be applied to methods, but its meaning is substantially different
than when it is applied to variables.

13

You might also like