Sie sind auf Seite 1von 33

OOP in Java

OOP in Java
2
At the end of this chapter you will be able to understand object oriented programming
concepts and will be able to utilize them in creating classes and methods.

SCOPE
2.1 Object Oriented Programming Concepts
2.1.1 Class
2.1.2 Abstraction
2.1.3 Encapsulation
2.1.4 Inheritance
2.1.5 Polymorphism

2.2 Creating Classes And Objects

2.3 Memory Management

2.4 Casting
2.4.1 Casting Primitive Data Types
2.4.2 Casting Objects
2.4.3 Casting Primitive Data Types To Objects Or Objects To Primitive Data Types

2.5 Constructors
2.5.1 Creating Multiple Constructors

2.6 Comparing Objects

2.7 Inheritance

2.8 Polymorphism

2.9 Command Line Arguments

2.10 Reflection Class

2.11 Case Study – College Student Enrollment System

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 27
OOP in Java

2.1 Object Oriented Programming Concepts

Object orientation is a paradigm shift in programming technology. Till now programmers


used the traditional approach of procedural programming. In procedural programming,
the programmer gives a list of instructions to the computer system and the computer
carries them out. As the code became large, there was a need felt to break the code into
blocks called procedures and functions. This is known as structured programming.

Structured programming did help in maintaining manageable chunks of code but at the
same time it had many drawbacks. Many times functions and procedures have to use data
outside their boundary. As a result of this, testing a module becomes very difficult, since
each module has to be checked to see if it is working properly as well as to see if the
value that it changes isn’t corrupted as a result. This problem is aggravated as the
program size increases. Another problem with the procedural programming was that data
was given secondary importance. Data is the most important thing in any application. In
fact data is the primary reason why the application exists. But in procedural programming
more emphasis was laid on how data is going to be manipulated with the help of
functions and procedures.

These problems are solved by the object-oriented methodology. Data is given the primary
importance in object oriented methodology. The core of the object-oriented technology is
the object. An object incorporates both data and methods that act upon that data. To
understand this better, consider any real life object, let us take the example of a pen. A
pen is an object that has characteristics (color, nib or ball point, body of the pen, etc.) and
behavior (a pen writes). Similarly in object oriented technology, an object comprises of
characteristics (data) and behavior (methods that operate on data). This concept is in
contrast to procedural programming where data and functions are loosely coupled.

When we talk about object-orientation, a lot of terms like object, classes, abstraction,
inheritance, polymorphism and encapsulation come to our mind. We have already
discussed what an object is, let us now explore the rest of the terms one by one.

2.1.1 Class

A class is nothing but a collection of similar objects. These objects must have the same
data structure and behavior or methods. For example, sparrow, parrot, and robin, all
belong to the class bird since they all have same attributes and behavior.

2.1.2 Abstraction

Abstraction is the process of identifying the items of interest to you from an application
domain perspective and leaving out the details that are not relevant to you. For example,
let us consider the Order Processing System. In this system, each item is given a unique
item number by which it is identified. This item will have a description, rate, quantity on
hand and reorder level status. Therefore the identity Item can have attributes as item

Chapter 2
28 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

number, description of the item, rate, quantity on hand, and reorder level. Note that we
could have taken some more attributes like color of the item, its dimensions, etc. But
these attributes are not really important in the Order Processing System so we have
omitted them from our design. This process of keeping the relevant details and discarding
the irrelevant ones is known as abstraction.

2.1.3 Encapsulation

As discussed earlier, an object incorporates both data and methods that act upon that data.
This process of bundling data and methods together is known as encapsulation. Let us
take the same example of order processing system again. We have already decided on the
data aspect, let us now identify the methods for the object item. The methods could be:
a) Printing the item details
b) Accepting the item details
c) Changing quantity on hand
d) Displaying value of the stock
e) Displaying the status whether an item has to be reordered or not
Object Item

Data Methods

Item No PrintDetails
Description AcceptDetails
Rate ChangeQOH
Quantity on hand DisplayValue
Reorder level ReorderStatus

Fig. 2.1 Encapsulation

This process of bundling data and methods together (as shown in fig. 2.1) is known an
encapsulation and it achieves data hiding because on the outside it just presents the
interface and the inner attributes remain hidden.

2.1.4 Inheritance

Inheritance is the sharing of attributes and operations among classes based on a


hierarchical relationship. Inheritance also facilitates reusability since all the attributes and
behavior of the main class are available to its sub-classes. For example, in the Order
Processing application, we have an object called Item (refer to fig. 2.1). Let us suppose
that the company deals in computer hardware. Then this item can be sub-classed into
Printer, Stationary, and Floppydisk. Now since all these sub-classes have some common
attributes like, itemno, description, rate, quantity on hand and reorder level, we have kept

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 29
OOP in Java

these under the super class Item. Printer sub-class will have all these attributes plus two
more attributes of its own – type of the printer(Laserjet or Inkjet) and number of pages
printed per minute. Stationary class again have all of the super class’s attributes plus one
more attribute – size of the paper. Floppydisk class also has all of the super class’s
attributes and two of its own – capacity and size. Fig. 2.2 shows this inheritance
pictorially.

Item

Item No
Description
Rate
Quantity on hand
Reorder level

Printer Stationary FloppyDisk

Type Size Capacity


PagesPerMinute Size

Fig. 2.2 Inheritance

2.1.5 Polymorphism

Polymorphism is the ability of a method or an operation to behave differently with


different objects. For example, show function would behave differently for class Printer
and class Floppydisk (refer to fig. 2.3). When applied to an object of Printer class, show
function would display Item No., Description, Rate, Quantity on hand, Reorder level,
type of the printer and pages printed per minute. And when show function is applied to an
object of FloppyDisk class, it would display Item No., Description, Rate, Quantity on
hand, Reorder level, Capacity and size.

Chapter 2
30 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

Item Details

Item No : 1000051
Description : HP Printer
Printer Rate : 10,500.00
Quantity on Hand : 112
Reorder level : 50
Type of Printer : LaserJet
Pages Per Minute : 8

Show Function

Item Details

Item No : 1001115
FloppyDisk Description : 3M Floppy disk
Rate : 215.00
Quantity on Hand : 567
Reorder level : 75
Capacity : 1.44 MB
Size : 3.5 inches

Fig. 2.3 Polymorphism

2.2 Creating Classes And Objects

Now that we are familiar with the object-oriented programming approach and the Java
programming constructs, let us now write Java program to create Item class. We have
already identified the data and methods for this class. The following Java code can be
written to create Item class.

class Item{
private int itemno;
private String description;
private float rate;
private int qoh;
private int rol;

public void display(){


System.out.println("Item Details");
System.out.println("------------");
System.out.println("Item Number : "+itemno);
System.out.println("Description : "+description);
System.out.println("Rate : "+rate);
System.out.println("Quantity on hand : "+qoh);
System.out.println("Reorder Level : "+rol);
}
public void changeQOH(int qty,char status){

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 31
OOP in Java

if (status=='A')
qoh=qoh+qty;
else
if (status=='S')
qoh=qoh-qty;
}
public void acceptDetails(int ino,String desc,float rt, int
qty,int reorder){
itemno=ino;
description=desc;
rate=rt;
qoh=qty;
rol=reorder;
}
}
Listing 2.1 Definition of Item class

Let us now understand this piece of code. This code has created a class called Item. This
class has five attributes and three functions. You would have noticed the access specifiers
– public and private, along with the definition of the attributes and methods of the class
Item. We will deal with access specifiers in detail in chapter 3. As of now you can
understand that if any attribute or method of a class is declared as public, it will be
available to all the other classes. If an attribute or a method of a class is declared as
private, it will not be able available to any other class except for the class in which it is
declared. Now since the data of an object should not be available to the object of other
classes, we have declared it as private in this example.

☞ You could have declared some of the attributes as public also. Declaring an
attribute or method as public or private is dependent on the application that you are
designing.
We want to design our application in such a manner so that methods should be the only
way by which one can access the data of Item class. This is the reason why all methods
have been declared as public in the above example. You would have also noticed a new
data type called String. String is not actually a data type, it’s a class defined in package
java.lang.

☞ Numbers and characters are not objects. They are primitive data types. This is the
reason for their definition and usage being different from the String object in the
above example.
Let us now understand how an object of a class is created. An object of the class Item can
be created by giving the following command:
Item I = new Item();
This command creates an object I of the class Item. In this command, new operator
creates an object, i.e., it allocates memory for the class’s data and a special method
defined in the class is called. This method is known as a constuctor. We will deal with
constructors later in this chapter.

Chapter 2
32 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

A method of a class can be called by using dot(.) notation. For example, changeQOH
method of class Item can be called as:
I.changeQOH(20,’A’);
where I is the object for which quantity on hand is being changed.

The complete listing of the program that defines Item class and uses it to create and
manipulate an object is given below:

class Item{
private int itemno;
private String description;
private float rate;
private int qoh;
private int rol;
public void display(){
System.out.println("Item Details");
System.out.println("------------");
System.out.println("Item Number : "+itemno);
System.out.println("Description : "+description);
System.out.println("Rate : "+rate);
System.out.println("Quantity on hand : "+qoh);
System.out.println("Reorder Level : "+rol);
}
public void changeQOH(int qty,char status){
if (status=='A')
qoh=qoh+qty;
else
if (status=='S')
qoh=qoh-qty;
}
public void acceptDetails(int ino,String desc,float rt, int
qty,int reorder){
itemno=ino;
description=desc;
rate=rt;
qoh=qty;
rol=reorder;
}
public static void main(String args[]){
Item I=new Item();
String d = new String("Nuts & Bolts");
I.acceptDetails(1,d,(float)23.56,100,23);
I.display();
I.changeQOH(20,'A');
I.display();
I.changeQOH(20,'S');
I.display();
}
}
Listing 2.2 Creating object of Item class (Item.java file)

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 33
OOP in Java

The working of this program is given below:

1. In the main function, an object I of Item class is created and an object d of String
class is created.
2. Method acceptDetails of object I is called which will allocate 1 to itemno, convert
23.56 to float and allocate it to rate, allocate 100 to qoh and 23 to rol. It also accepts a
String object d and allocates it to description.
3. Method display is called which will display the item details.
4. Method changeQOH is called with two parameters – 20 and ‘A’. This will add 20 to
the existing qoh.
5. Method display is called again.
6. Method changeQOH is called again with two parameters – 20 and ‘S’. This will
subtract 20 from the existing qoh.
7. Method display is called again.

The output of this program is given below:

Item Details
---------------
Item Number : 1
Description : Nuts & Bolts
Rate : 23.56
Quantity on Hand : 100
Reorder Level : 23

Item Details
---------------
Item Number : 1
Description : Nuts & Bolts
Rate : 23.56
Quantity on Hand : 120
Reorder Level : 23

Item Details
---------------
Item Number : 1
Description : Nuts & Bolts
Rate : 23.56
Quantity on Hand : 100
Reorder Level : 23

Note that the methods of the same class like acceptDetails, can access the class variables
or methods directly. For example, in acceptDetails function, we gave the command
itemno=ino, which assigns the value of variable ino to itemno. But in the main function
the method display of class Item is called as I.display(). This means that you are not able
to access the attributes or methods of a class in another class or function directly. You
will have to access methods or attributes through an object, i.e., you must create an object
of that class first and then access its public attributes or methods via that object.

Chapter 2
34 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

2.3 Memory Management

You have seen that new operator can be used to create a new object in Java. This operator
allocates right amount of memory to each object’s data. Memory management in Java is
dynamic and automatic. This simply means that it is perfectly possible for you to create
just a reference to an object and allocate memory to it at a later point of time with the
help of new operator. This is depicted in the example given below:

…….
Item I;
…….
…….
I = new Item();
……

Let us now see how memory is allocated to objects of a class. Each object of a class will
have memory allocated for its individual attributes, but all the objects of the same class
will share the same methods. This simply means that whenever an object of a class is
created with the help of new operator, memory is allocated for its attributes and not for its
methods. This is depicted in fig. 2.4.

Memory

Methods of class Item


acceptDetails
display
changeQOH

Item A Item B

1 2
Nuts & Bolts Hammer
23.56 75.89
100 156
23 50

Fig. 2.4 Memory Management

Since memory management in Java is automatic, you don’t have to deallocate the
memory that an object uses. Java has a garbage collector that looks for the objects that
are no longer in use and reclaims the memory used by those objects.

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 35
OOP in Java

Many times an object has to perform certain operations when it is destroyed. For
example, a program could be holding some resource like a file handle, or a window
character font, which you might want to free before that object is destroyed. For this
purpose you can override a method called finalize(). This method is invoked just before
that object is reclaimed by the garbage collector. This process of defining the finalize()
method is known as finalization. The general form of finalize() method is:
protected void finalize(){
………….
………….
}

However, you must note one thing. There is no way of knowing when the garbage
collector is invoked and finalize() method is called just before the garbage collection. For
this reason you can never be sure of when and also if at all your finalize() method will be
invoked.

☞ You have to explicitly allocate memory to objects with the help of new operator,
but you don’t have to explicitly free it.

Runtime class

Runtime class encapsulates the run-time environment. Since the run-time environment
already exist, you cannot instantiate the Runtime object. You can, however, get the
reference to the current run-time environment with the help of getRuntime() method. You
can explicily call garbage collection by using method gc(). The following piece of code
invokes the garbage collection.

………………
………………
Runtime r=Runtime.getRuntime();
r.gc();

2.4 Casting

In a Java program, many times a data value of one type has to be converted to a value of
another data type. For example, one might have to convert an int to float or a float to
double. Casting is the process of getting a new value that has a different data type than its
source. Casting can take place between primitive data types (int, float, boolean, etc.) or
between objects (String, Point, Integer, etc.) or between a primitive data type and an
object.

Chapter 2
36 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

2.4.1 Casting Primitive Data Types


Casting between data value of primitive data types simply converts a data value of a
primitive data type to another primitive data type. However, boolean values cannot be
used in casting as they can hold only two values true or false. Casting usually happens
among numeric values. In case the destination can hold a larger value than the source (as
in the case of converting int to long, casting is done automatically. This means that one
can use an int as long. This is because when a smaller value is converted to a larger value,
there is no loss of data involved.
However, if the destination cannot hold larger value than the source, explicit casting must
be done. Explicit casting is done in the following way:
(data type)value

The following piece of code converts a float value to an int value.


………….
int i;
float f=6.7;

i=(int)f;
………….

However, data will be lost in this case. Variable i will have a value 6 since it will be able
to hold only integer part of the data. Another example given below converts an integer to
double.
………….
int i=1078;
double d;

d=(double)i;
………….

2.4.2 Casting Objects

As a primitive data type value can be converted to another primitive data type value, an
object of a class can also be converted to an object of another class. But both these
classes must be related to each other by inheritance, i.e., one class must be a subclass of
the other class. Here also casting can either be implicit or explicit.

Implicit casting happens when an object of smaller type is casted to an object of larger
type. This means that an instance of subclass can be used wherever an instance of a super
class is expected without explicitly casting. This is because all the attributes and methods
of a super class are automatically available to all of its subclasses. Refer to fig. 2.2 which
shows the inheritance relationship among Item, Printer, Stationary and FloppyDisk
classes. Item is the super class and rest are its subclasses. If there is a function that
accepts an object of Item class, it will also accept an object of Printer or Stationary or
FloppyDisk class.

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 37
OOP in Java

However, if an object of subclass has to be casted to an object of super class, explicit


casting must be done. There is one more thing that one must keep in mind while doing
explicit casting – explicit casting might result in loss of information. This is because
subclass will contain more functionalities than its super class. To cast an object to another
class the following operation can be used:
(classname)object

Refer to fig.2.2 again and observe the code given below:

Item I = new Item();


Printer P = new Printer();
I=P; // valid statement, implicit casting done
P=I; // invalid statement, explicit casting required
P=(Printer)I; // valid statement

2.4.3 Casting Primitive Data Types to Objects or Objects to Primitive Data Types
Casting an object to primitive data type or vice-versa is not allowed at all in Java. This is
because primitive data types do not follow the concept of a class and hence they are very
different from objects. Since this feature of casting an object to primitive data type or
vice-versa is not allowed, Java has provided its users with an alternative. java.lang
package include classes that correspond to primitive data type. For example, it has a class
called Integer in place of primitive data type int, similarly there are classes like Boolean,
Byte, Character, Long, Void, Double, Float, etc for each of the primitive data type.
To convert an object to primitive data type or vice-versa, you can use the methods of that
class. For example, to convert a String object to an int you can write the following code:
String str = new String(“4578”);
int i = Integer.parseInt(str);

In the above code we have made use of method parseInt of Integer class to get the integer
value of the String object str.

2.5 Constructors
In section 2.2 we had a brief introduction to constructor. Let us now understand
constructors in detail. Constructors are class methods that are used to initialize object’s
data. Constructors can be declared in the same way as any other method of a class is
declared. However, a constructor will not have any return type (not even void type should
be mentioned) and the name of the constructor is same as the name of the class. The
following piece of code defines a constructor for the Item class.
Item(){
itemno=0;
description = new String();
rate=0.0f;
qoh=0;
rol=0;
}
Listing 2.3 Constructor for class Item

Chapter 2
38 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

This constructor assigns value to the object’s data whenever it is called. A constructor
can be called as:
Item I = new Item();

Now in program listing 2.2 we did initialize an object I in the same manner as given
above. But at that time we did not define any constructor method, but still the program
didn’t give us any error. That was because Java automatically provides every class with a
default constructor whenever user does not give any. Therefore, in program listing 2.2,
the default constructor of class Item was called. If the user writes a constructor method in
the class, that method will be called when an object of that class is created.

2.5.1 Creating Multiple Constructors

A class can have multiple constructors also. But the question is why would anyone need
multiple constructors for a class. Since constructors are the way to initialize an object,
one might want to create objects in a variety of way. For example, one might want that
when Item I = new Item() command is given, all numeric data must be assigned
0 and all character data must be assigned blank spaces. That is what constructor defined
in listing 2.3 is doing. Now, one might also want that when Item I = new
Item(str) is given (where str is a String object), all numeric data must be assigned a
value 0 and description must have a value given by the String str. Similarly one can
create other types of constructors defined for the class Item. The constructor that is called
in the program will depend on the way an object was created at run time. Listing 2.4
gives the complete code for Item class with two constructors and it also shows how
objects can be created in different ways.

class Item{
private int itemno;
private String description;
private float rate;
private int qoh;
private int rol;

public void display(){


System.out.println("Item Details");
System.out.println("------------");
System.out.println("Item Number : "+itemno);
System.out.println("Description : "+description);
System.out.println("Rate : "+rate);
System.out.println("Quantity on hand : "+qoh);
System.out.println("Reorder Level : "+rol);
}

public void changeQOH(int qty,char status){


if (status=='A')
qoh=qoh+qty;
else
if (status=='S')
qoh=qoh-qty;

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 39
OOP in Java

public void acceptDetails(int ino,String desc,float rt, int


qty,int reorder){
itemno=ino;
description=desc;
rate=rt;
qoh=qty;
rol=reorder;
}

Item(){ // Constructor 1
itemno=0;
description=null;
rate=0.0f;
qoh=0;
rol=0;
}
Item(String str){ //Constructor 2
itemno=0;
description=str;
rate=0.0f;
qoh=0;
rol=0;
}
}
Listing 2.4 Class Item with constructors (Item.java file)

import Item;

class TryItem{
public static void main(String args[]){
Item i=new Item(); // Calls Constructor 1
i.display();

String d = new String("Nuts & Bolts");


Item j=new Item(d); // Calls Constructor 2
j.display();

/* Invalid as the declaration does not match any constructor


defined in the class */
Item k=new Item(1,d);
k.display();
}
}
Listing 2.5 Creating Item objects (TryItem.java file)

Chapter 2
40 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

☞ How does the default constructor initialize object’s data?

In listing 2.4 the line where an object k is created will give a compile time error since the
class does not have any matching constructor. The class Item has only two constructors –
one that accepts nothing and second that accepts an object of type String. This call tries to
call a constructor that accepts an integer and a String object, which does not exist in the
class. Once you have created this Item.java file, compile it to create Item.class file.
To create an Item object, include the Item class in the program where the object has to be
created. In listing 2.5 this task is done with the help of statement import Item (Item
Class should be in the same directory). This statement includes the
definition of Item class at compile-time.

In listing 2.5, objects i and j are created in different manner and thus they call different
constructors. But name of both the constructors is the same. This is called constructor
overloading. But the question is how does compiler decides which call is for which
constructor in such a situation? The explanation for this is simple. A function is
recognized by its signature which consist of function name, number of arguments it
accepts and argument type. A constructor is also a function and thus the same definition
of signature applies to it also. When a call to constructor is made, Java matches the
signature of the function that calls the constructor to the signature of the constructor
declared in the class. Then it calls the constructor that has the same signature as the
calling function.

☞ When two functions of same name but different signatures are defined, it is known
as function overloading.

2.6 Comparing Objects

While dealing with primitive data types comparisons between two primitive data values
can be done by using equal (==) operator. For example, the following code declares two
int data values and then compares them.

class Compint{
public static void main(String args[]){
int x=33;
int y=33;

if (x==y)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
Listing 2.6 Comparing primitive data types (Compint.java file)

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 41
OOP in Java

The output of this program would be “Equal” since both x and y have the same value.
Now let us write the same program by using Integer class objects.

class CompInteger{
public static void main(String args[]){
Integer x=new Integer(33);
Integer y=new Integer(33);

if (x==y)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
Listing 2.7 Comparing objects using == (CompInteger.java file)

Memory
The output of this program, however, would be “Not
Equal” even when both objects have the same value
X Y 33. The reason is that == compares two objects and
not the value of the objects and since x and y are
33 33 different objects, the output is “Not Equal”. This is
explained in fig. 2.5

Fig. 2.5 Memory allocation for


different objects
The same program would give the output as
Memory “Equal” when object y is declared as:
X Y Integer y;
y=x;

This is because now only one object has been


created with a value 33. Object y is not allocated
33
memory as of now since the constructor method
has not been used. So y is simply a reference to
an object of type Integer but it is not pointing to
Fig. 2.6 Memory allocation for any object right now. After the statement y=x is
variables that point to the same object given, y starts pointing to the same object as x is
pointing to. Fig. 2.6 makes this thing clear.

Therefore, two objects can’t be compared using == operator in terms of the value they
contain. To compare the values contained by two objects equals() method can be used.
Program listing 2.8 gives the code for comparing values contained by two Integer objects.

Chapter 2
42 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

class CompInteger{
public static void main(String args[]){
Integer x=new Integer(33);
Integer y=new Integer(33);

if (x.equals(y))
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
Listing 2.8 Comparing the values contained by two Integer objects (CompInteger.java file)

2.7 Inheritance

We had a small introduction to the concept on Inheritance in section 2.1.4. Let us now
understand how it is implemented. We have already declared the Item class with five
attributes, three methods and two constructors (refer to program listing 2.4). Let us create
a subclass of Item class called Printer, which has two more attributes – type of printer
and number of pages printed per minute.

import Item;

// Defining Printer class


class Printer extends Item{
String type;
int ppm;

Printer(){ // Constructor 1
super();
type=null;
ppm=0;
}
Printer(int ino,String desc,float rt,int qty,int
reorder,String type,int ppm){
super(ino,desc,rt,qty,reorder); // Constructor 2
this.type=type;
this.ppm=ppm;
}
public void display(){
super.display();// Calling display method of super class
System.out.println("Type of Printer : "+type);
System.out.println("Pages per minute : "+ppm);
}
}
Listing 2.9 Printer class – a subclass of Item (Printer.java file)

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 43
OOP in Java

// TryInherit class that will make use of Item and Printer class
objects
import java.lang.*;
import Printer;

class TryInherit{
public static void main(String args[]){
Item i=new Item(1,"Mouse",500.89f,1200,200);
i.display();
Printer p=new Printer(2,"Inkjet Printer", 10000.75f,
200,35, "6P", 6);
p.display();
}
}
// End of TryInherit class
Listing 2.10 Implementing Inheritance (TryInherit.java file)

There are two new terms introduced in listing 2.9 – super and this. The super keyword is
used to refer to the super class. In constructor 1 of Printer class, The statement super()
actually calls the constructor method (number 1) of super class Item. Similarly in
constructor 2 of Printer class, statement super(ino,desc,rt,qty,reorder) calls
the constructor method (number 2) of super class Item.

The display function of Printer class calls the display function of the super class to
display first five attributes and then prints the extra two attributes. This means that both
subclass and super class can have functions with the same name.

Constructor 2 of Printer class also makes use of this keyword. this keyword is used to
refer to the current object. Note that one of the arguments of the constructor method 2 has
the same name as the object’s attribute (type). Now while assigning value of the
argument type to the object’s data type, it should be clear that which variable is giving the
value and which one is accepting the value. Therefore the statement this.type=type
was given. This statement implies that the object’s data “type” will have the same value
as the argument type of the constructor. Fig. 2.7 shows the memory allocation and
working of this program when the methods i.display() and p.display( are called.

Chapter 2
44 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

Printer class functions Item class functions


Printer() Item()

Printer(ino,desc,rt,qty,reorder, Item(ino,desc,rt,qty,reorder)
type,ppm)
display()
display() display()

itemno
description
rate
itemno
qoh
description display()
rol
rate
type
qoh
ppm
rol
Object p

Object i
Fig. 2.7 Working of TryInherit.java program

2.8 Polymorphism

As said earlier, Polymorphism is the ability of a function to respond differently to


different objects. Polymorphism is of two types – static polymorphism and dynamic
polymorphism. In Static Polymorphism, the function that has to be called is known at
compile time itself. For example, if two functions with the following signatures are
declared in a program,
changeQOH(int, char)
changeQOH(int)
and the command given in the program is
changeQOH(30)

The second function will be called and this is determined at compile-time itself. The fact
that the second function will be called in this case is determined by the type and number
of arguments sent to the function. Since only one argument is sent, the second function is
called. If two arguments (one int and another char) were sent, the first function would
have been called. This feature is also known as Function Overloading or Early Binding.

Dynamic Polymorphism is also known as Late Binding. In dynamic polymorphism, the


decision of the function to be called is resolved at run-time instead of compile-time. Let
us take an example to make things more clear.

We have already declared Item and Printer class files. Printer is a subclass of Item class.
It is possible to declare a reference to the super class (Item) and then at run-time

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 45
OOP in Java

depending on what the user enters, either an Item or a Printer object can be declared
(refer to listing 2.11).

import Printer;
import java.io.*;

class TryPoly{
public static void main(String args[]){
Item i;
int ch=0;

while (ch!='P' && ch!='N')


{
System.out.println("Enter N to add a normal item or P
to add a Printer");
try{
ch=System.in.read();
} catch(IOException e){
System.out.println("Error");}
}

if (ch=='P')
i=new Printer(1,"Laserjet",20000f,100,25,"III Plus",8);
else
i=new Item(1,"Mouse Logitech",300f,100,20);
i.display();
}
}

Listing 2.11 Implementing dynamic polymorphism (TryPoly.java)

Ignore the try…catch block of the code in listing 2.11. We use try…catch block to handle
errors that might occur in a program. We will deal with them in detail in chapter 5.
System.in.read is a method that is used to accept an input from the user. Note that
variable i is declared as a reference to class Item but at runtime i will be able to hold
either an object of Item class or Printer class. If the user enters N at runtime, the output of
this program would be:

Item Details
---------------
Item Number : 1
Description : Mouse Logitech
Rate : 300
Quantity on Hand : 100
Reorder Level : 20

Chapter 2
46 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

If the user enters P the output would be:

Item Details
---------------
Item Number : 1
Description : Laserjet
Rate : 20000
Quantity on Hand : 100
Reorder Level : 25
Type of Printer : III Plus
Pages per minute : 8

Printer class functions


Printer()
itemno
description Printer(ino,desc,rt,qty,reorder,
rate type,ppm)
qoh
rol display()
type
ppm
P

Object p
User enters Item class functions

Item()
N itemno
description Item(ino,desc,rt,qty,reorder)
rate
qoh
rol
display()

Object i
Fig. 2.8 Dynamic Polymorphism

Note that depending on the user input either display function of Item or Printer class is
called. This concept is known as Dynamic Polymorphism or Late Binding.

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 47
OOP in Java

2.9 Command Line Arguments


Command line arguments are the arguments that can be passed to the Java program at the
command line. A Java application program is run by giving the command:
java <class file name>

Therefore to run TryPoly.class file, the command is:


java TryPoly

To pass arguments to a program the following command can be given:


java TryPoly c1 c2 c3 c4 c5

Here c1 is the first argument, c2 is the second argument, c3 the third and so on. Note that
a space is necessary between two arguments. The advantage of accepting arguments at
command line is that the application program become more generic. Let us consider
tryPoly.java program. Instead of asking at runtime which type of object to create (N or
P), command line argument could have been passed to the program.

Let us now see how Java handles command line arguments. If an application accepts
arguments at command line, Java stores these arguments as an array of strings and passes
them to the main() function. Then the application program handle it in any way it wants
to. Listing 2.12 accepts command line arguments and then print them inside the main
function.
public class TryMainArguments{
public static void main(String[] args)
{
int i=0;
for (i=0;i<args.length;i++){
System.out.println("Argument "+(i+1)+" : "+args[i]);
}
}
}
Listing 2.11 Printing Command Line Arguments (TryMainArguments.java)

Now after compiling this file, if the command is given as:


java TryMainArguments one two three

The command line arguments one, two and three would be passed as an array of Strings
to TryMainArguments application program. The program would accept this array as args
in its main function. This program runs a loop from 0 to the length of the array args
minus 1 and prints each argument. The output of this program would be:
Argument 1 : one
Argument 2 : two
Argument 3 : three

Let us now convert TryPoly.java program so that it can accept either N or P as a


command line argument and then create either Item object or Printer object.

Chapter 2
48 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

class TryPoly1{
public static void main(String args[]){
Item i;
if (args.length!=1){
System.out.println("Wrong number of arguments");
System.exit(0);}

if (args[0].equals("P")){
i=new Printer(1,"Laserjet",20000f,100,25,"III
Plus",8);
i.display();}
else
if (args[0].equals("N")){
i=new Item(1,"Mouse Logitech",300f,100,20);
i.display();}
else{
System.out.println("Invalid value...");
System.exit(0);}
}
}
Listing 2.12 Implementing Polymorphism through Command Line Arguments (TryPoly1.java)

Program Listing 2.13 accepts a number as a command line argument and print fibonacci
series from 0 till that number.
class Fibonacci{
public static void main(String args[]){
int a=0,b=1,c;

if (args.length!=1){
System.out.println("Wrong number of arguments");
System.exit(0);}
if (Integer.parseInt(args[0])<=0){
System.out.println("Value must be greater than
zero");
System.exit(0);}

System.out.println("Fibonacci series (<"+args[0]+")");


System.out.println(a);
System.out.println(b);
do{
c=a+b;
if (c>Integer.parseInt(args[0]))
break;
System.out.println(c);
a=b;
b=c;
} while(true);
}
}
Listing 2.13 Fibonacci series through Command Line Arguments (Fibonacci.java)

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 49
OOP in Java

2.10 Reflection Class

Reflection or Introspection enables one Java program to learn details of any Java class.
One can find the variables, methods and constructors of a class with the help of
reflection. Listing 2.14 shows a code that prints all the methods of a class called Adler32.

import java.util.zip.Adler32;
import java.lang.reflect.*;

class TryReflect{
public static void main(String args[]){
Adler32 d=new Adler32();
int i;

Class cname = d.getClass();


System.out.println("Class Name : "+cname.toString());
Method[] methods = cname.getMethods();
for (i=0;i<methods.length;i++){
System.out.println("Method "+(i+1)+" : "+methods[i]);
}
}
}
Listing 2.14 Printing methods of class Adler32 (TryReflect.java)

In this program, an object of class Adler32 is created. Variable cname stores the class
name of this object, which will be Adler32. methods is an array of object Method
(Method is one of the classes in java.lang.reflect). The function getMethods gets all the
methods of class represented by cname(i.e., Adler32). Then all these methods are printed
one by one. In case methods of another class are to be printed, simply change the line
number 6 of this program an create an object of that class. This program will print the
methods of that class. (Don’t forget to import that class in your program). The output of
this program would be:

Class Name : class java.util.zip.Adler32


Method 1 : public boolean
java.lang.Object.equals(java.lang.Object)
Method 2 : public final native java.lang.Class
java.lang.Object.getClass()
Method 3 : public native int java.lang.Object.hashCode()
Method 4 : public final native void java.lang.Object.notify()
Method 5 : public final native void java.lang.Object.notifyAll()
Method 6 : public java.lang.String java.lang.Object.toString()
Method 7 : public final void java.lang.Object.wait() throws
java.lang.InterruptedException
Method 8 : public final native void java.lang.Object.wait(long)
throws java.lang.InterruptedException
Method 9 : public final void java.lang.Object.wait(long,int)
throws java.lang.InterruptedException
Method 10 : public long java.util.zip.Adler32.getValue()

Chapter 2
50 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

Method 11 : public void java.util.zip.Adler32.reset()


Method 12 : public void java.util.zip.Adler32.update(int)
Method 13 : public void java.util.zip.Adler32.update(byte[])
Method 14 : public void
java.util.zip.Adler32.update(byte[],int,int)

Program Listing 2.15 shows the code for TryReflect1.java that prints all constructor
methods of class Alder32. The only difference between this code and listing 2.14 is that
here we have created an array of Constructor object instead of Method object (as in
listing 2.14). And then getConstructors method is used to get all constructors of that
class.

import java.util.zip.Adler32;
import java.lang.reflect.*;

class TryReflect1{
public static void main(String args[]){
Adler32 d=new Adler32();
int i;

Class cname = d.getClass();


System.out.println("Class Name : "+cname.toString());
Constructor[] cs = cname.getConstructors();
for (i=0;i<cs.length;i++){
System.out.println("Constructor "+(i+1)+" : "+cs[i]);
}
}
}
Listing 2.15 Printing Constructor methods of class Adler32 (TryReflect1.java)

The output of this program would be:


Class Name : class java.util.zip.Adler32
Constructor 1 : public java.util.zip.Adler32()

Again, to see the constructor methods of any other class, create an object of that class and
see its constructor methods in the same way as in Listing 2.15.

2.11 Case Study–College Student Enrollment System

Given below is the Case Study for Student Enrollment System from a bigger problem
domain of a College System.

Problem Statement :

The faculty determines the courses and the subjects offered for the admission. Subjects
may be taken as a part of number of courses. Subjects will either be core subjects or
optional subjects. Generally the number of seats available for a course will be controlled.
All courses will have established entrance qualifications. The enrollment process begins

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 51
OOP in Java

when an applicant submits an application for a course. The applicant will also select the
course and the optional subject he or she wishes to take. The applicant will submit his or
her personal details and the results of previous examinations taken. The applicant’s
application is first checked for qualification and then for course and subject availability.
If places are available and the applicant is qualified, he or she is enrolled as a student.

1+ Subject
Course

concerns

Application

Core Optional
submits
selects
Applicant
enrolled
Student

Fig. 2.9 Class Diagram for Student Enrollment System

☞ The notation used in the above diagram is OMT(Object Modelling Technique)


where: indicates class

indicates Inheritance

indicates containment

1+ indicates course contains one or more subjects


The class diagram identifies the required classes and their associations in the system. To
implement this case study we will make certain assumptions for cutting down the scope
of the problem domain. The assumptions are:
• The last date for all courses is same
• The number of students in each course is 5 (but can be extended to any number later)
• The available courses are “MDMC”, ”UCO”, and “C++” (can be extended by the
programmer)
• The available subjects are “C”, “C++”, “OOADS”, “JAVA”, “NT”, “UNIX”, “VB”,
“VC”, “ORACLE”.
• The first five students who are above the cutoff of 75% will get admitted.
• The qualification that the user enters will not be cross checked from any records and
is assumed to be authentic.

Chapter 2
52 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

Now we will define some of the classes with their methods and attributes.

public class Subject{


String sname;

Subject(String name){
this.sname = name;
}
}
Listing 2.16 Code for Subject.java

public class CoreSubject extends Subject{


CoreSubject (String name){
super(name);
}
public void setName(String name){
sname=name;
}
}
Listing 2.17 Code for CoreSubject.java which is inherited from Subject class

public class OptSubject extends Subject{


OptSubject(String name){
super(name);
}
public void setName(String name){
sname=name;
}
}
Listing 2.18 Code for OptSubject.java which is inherited from Subject class

Similarly we can define the rest of the classes in the class diagram. We will continue with
the case study in further sessions.

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 53
OOP in Java

SUMMARY
♦ An object has characteristics as well as behavior, for example, a chair has the
characteristics (it is made up of wood, it has four legs, etc.) and behavior (one can sit
on it).

♦ A class is a set of similar objects, for example, Maruti, Fiat, Santro all belong to the
class Car.

♦ Encapsulation is the process of bundling data and methods that act on that data
together into a single unit called class.

♦ Inheritance is the means by which more classes can be created from existing one.

♦ The class that gets created by inheritance is known as subclass and the class from
which the subclass is created is called super class.

♦ A subclass inherits all data and methods from its super class.

♦ Multiple subclasses can be created from a super class.

♦ new operator is used to create an object in Java. Memory management in Java is


automatic so there is no need of deallocating the memory occupied by an object.

♦ One primitive data type can be created into another primitive data type by giving the
command – (data type)value.

♦ One object can be cast into another object only if they are related to each other by
inheritance.

♦ There is no way to convert an object to primitive data type or vice-versa directly. You
can use methods of objects like (Integer, Character, Byte, Float, etc.) to achieve this.

♦ Constructors are the methods that get called when an object is created with the help of
new operator.

♦ When two or more constructors with different argument type or numbers are created,
it is known as Constructor Overloading.

♦ When two or more functions with the same name but different type or number of
arguments are created, it is known as Function Overloading.

♦ == operator is used to compare primitive data types.

♦ equals() method can be used to compare the value of two objects.

Chapter 2
54 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

♦ == operator when used with objects returns whether both of them point to the same
object in memory.

♦ Polymorphism is the ability of a function to respond differently with different objects.

♦ In Static polymorphism, the decision of which function should be called is resolved at


compile time, for example, Function or Constructor Overloading.

♦ In Dynamic Polymorphism, the decision of which function of which object should be


called is resolved at runtime.

♦ Command line arguments make a program more generic.

♦ Reflection class can be used to inspect the data, methods and constructors of any
unknown class and then using it in your own program.

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 55
OOP in Java

SELF ASSESSMENT
State True of False:

1. All data and functionality in a Java program is organized into classes.

2. The source file name must correspond to the public class name.

3. Java allows us to declare and allocate objects in a single statement.

4. A subclass of one class may be a super class of another class.

5. You have to explicitly free the memory occupied by the objects in Java.

6. A primitive data type can be cast into an object directly.

7. Two constructors can have the same number and type of arguments in a class.

8. The == operator can be used to compare two objects.

9. The type of command line arguments can be other than String.

10. A Java program can accept as many number of arguments as possible.

Fill in the blanks:

1. Objects are ____________ of classes.

2. __________ operate on data in the class.

3. The methods that have the same name as the class are called ____________.

4. Objects are instantiated using ______ operator.

5. The getMethod() is a method of ____________ class.

Chapter 2
56 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

LAB EXERCISE
1. Create a class called Employee that will have the following attributes:
Employee Number
Name
Address
Date of Birth
Hiredate

The class must have the following methods also:


i) A constructor that accepts nothing and initializes all numeric attributes with 0
and String with null
ii) A constructor that accepts all attribute values
iii) A method called display() that displays all attributes
iv) A method called changeAddress(String address) that changes the address of
an employee

Create two subclass of Employee class called Wagers and Salaried. The Wagers
should have additional attributes as days worked and salary per day. The Salaried
should have additional attributes as basic salary, da, hra, pf, and other deductions.
Both of these classes should have display() methods of their own that displays all
details of an employee and the type of employee – (Salaried or Wager).

i) Test the methods of Employee class.


ii) Test the display() method of all three classes.
iii) Create an object of Wagers class and another object of Employee class. Type
cast the object of Wagers class to an object of Employee class.
iv) Create two objects of a class that have identical information and use ==
operator to check if it gives you the right result.

2. Write a program that accepts numeric command line arguments and adds all of them.
For example, if the argument list is:
100 100 134 150 300 200

The output should be:


984

3. Print all the methods and constructors of Button class.

4. Study the case study given below and create the broad outline of the classes in it.

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 57
OOP in Java

Human Resource Department of ABC Ltd. handles nearly 10 applications per employee
everyday. Errors in filling forms translate into lost-time and money. They want to
automate the task of employee filling the forms correctly without any errors so that they
can be further processed and added to the database. The employee has to fill all the
related forms (not necessarily in any sequence). We will curtail the number of forms to be
filled up (for the purpose of cutting down the problem domain). There are two forms:
ABC Ltd Provident Fund Scheme and Employee Information Sheet.

Employee Information Sheet

Chapter 2
58 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
OOP in Java

Provident Fund Scheme

We will continue with the case study in the coming sessions.

Chapter 2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 59

Das könnte Ihnen auch gefallen