Beruflich Dokumente
Kultur Dokumente
1.0 Introduction
Following the Object Oriented concept, we can say that Pratima or Pradip is
an object belonging to the Class Friend. As you can have many friends, all of them can
be described by a common description blueprint (or template) called Friend. In the same
way a particular book can be described by a description blueprint called Book which
should have attributes like book_name, author_name, publisher, price, ..., etc.
Thus the blueprint with the help of which many similar objects can be described
and manipulated in an Object Oriented Program (OOP) has been given the name Class.
Like any OOP language, Java takes help of class definitions to create required number of
software objects to solve problems by a computer. A class or the objects’ blueprint should
have a unique name by calling which a collection of attributes and methods (Fig-1.1)
can be manipulated as a software unit.
Class Name
Attribute1
Attribute2
State | Fig:1.1 A Class blueprint
|
attributeM
Behaviour Method1
Method2
|
|
MethodN
As shown in Fig 1.1, a Class can be regarded also as a special data type which
encapsulates a bundle of attributes (which describes the State an Object) and a collection
of methods (exhibiting all common behaviour of objects). In a Java program, many
similar objects can be created from a Class definition.
Java being an Object Oriented Programming language, a java program
consists of one or more Class definitions out of which Objects are created and
manipulated by allowing messages (Fig-1.2) to pass in between them.
Class-A Class-B
Obj-i.methodx(p)
Obj-i Obj-k
Message
As shown in Fig-1.2, Obj-k intends to get a work done by calling the method
methodx(p) which obj-i is capable of performing. A message is normally passed in the
form of --
Obj-i.methodx(p)
-- where p stands for the parameter(s) to be passed with the method while
calling, if any. Method invocation without any parameter passing is quite possible and
often done.
class FirstJava
{ public static void main() {
int x, y;
int result;
x = 10;
y = 20;
result = x+y;
If you run this program, the value of (x + y) will be displayed. The class
FirstJava has a method main() which starts program execution. To display the output
result, a method -- println() ( available within java library class System.out) has been
utilized.
Picture 1.2 (Top) Executed by clicking void main() menu (bottom) Terminal Window
showing the output result
No one, of course, will use java programs to solve such simple problems. To write
programs for solving complex problems, we have to identify the objects, classes, and the
interactions that can take place between objects specific to the particular problem
domain.
Suppose, a customer – Amit wants to withdraw a sum of Rs. 500/- from his
savings account (“xyz..”) from a bank (“abc..”). He will hand over the cheque to a clerk.
The clerk will first verify the signature – if found OK; then the balance available with the
account will be checked. Again, if (balance > withdraw_amount ) then the payment
order will be issued, the balance will be updated, cash will be handed over and finally
the transaction will be closed by stamping “paid”. We see that there are several actions
that are to be carried out by maintaining a proper sequence so that no error creeps in the
process of transaction.
Taking help of a computer program one may carry out such transactions. The real-
life objects involved in such bank transactions can be identified as –
Class Bank: a bank (having bank_name, branch,....etc) where Amit has an account;
One Java program can help a bank-clerk in taking routine actions. That
program can make use of software objects created out of the defined Classes like --
Customer, SBAccount, Cheque, etc. Besides instance variables to accept attribute values,
appropriate functions or methods are to be encapsulated with each Class type, such as --
with Customer : checkCustomerName(name);
verifyAccNo(accNo); ... ... ...etc
gives checkBalance
verify
signature
Amit AccNo ... updateBalance
Hand over
cash Bank Clerk allowWithdraw
From Fig-1.3 we find that real-life actors (like Amit, Bank-Clerk, ...) are interacting
with either paper records or software objects ( like customer-records, SBAccount records,
etc.) to achieve the desired goal of error-free cash withdrawal. So a system can be
divided into actors or users and software objects.
To have computer support in bank transactions, a program can be written in Java
to process cheque verification, searching customer records, verifying and updating
SBAccounts, etc. The question is how to develop a general program by using which cash
withdrawal for any customer will be possible. Customers are many, SBAccounts are many,
cheques are many – but each individual case can be handled by creating objects of
respective Classes. The customer Amit can be regarded as an object of the Class –
BankCustomer; Amit’s SBAccount can be taken as an object of another Class -
SBAccount; Amit’s cheque can belong to the Cheque Class of the Bank, etc.
Therefore, the bank transaction project should have defined classes like
Customer, SBAccounts, ... etc. A typical BankCustomer class definition blueprint is shown
below: --
Let us now expand our concept about software objects. From a class definition
many objects with similar attributes and functions or methods can be created in a computer
memory. For example, from a defined Class – School-- details of many schools can be
collected and stored by a java program. Attribute values or an object’s state (like name,
address, etc.) will be different for different schools. Those values can be set by a method
(say) – setDetails() – and checked by calling the displayDetails() method coded within
the Class definition.
/**
* Two methods defined -
*/
public void displayName() // no need of any parameter to pass
{
System.out.println(" School Name is :" + name);
}
public void displayAddress( ) // no need of any parameter
{
System.out.println(" School Address is :" + address);
}
}
Please note that the class School has not included any main() method but has made use of
methods like displayName() and displayAddress().
Use BlueJ editor to enter the java program shown in example-1.2. By clicking the
School box on new School() menu, create an instance of School – school_1 and see what
happens when you call the methods – void displayName() or void displayAddress()
associated with that object.
From a defined Class, one can create as many objects as required with different
values of instance variables.
As methods, included in a class, are functions -- so each one of them must return a
value of some data type. In general description, the data type of the return value has been
shown as <return type> or <rets>. When no value is returned by a function but some
action is only taken, the return type is set as void. That is why void as <return type> is used
with displayName() or displayAddress() method.
Of course, some function may require one or more input parameter(s) to pass while
calling a method. Data type of each such parameter, when needed should also be mentioned
explicitly while defining that method.
By pre-defining a class, a special user defined data type is kept ready for
subsequent use in a Java program (which is nothing but a collection of one or many such
class definitions out of which one must contain a main() method). To create objects out of a
defined class – you have to make use of the new operator.
Thus N-numbers of school objects can be created out of the class defined as
manySchool.
• Run Example-1.3 in BlueJ environment and verify that as many objects can be
created from the manySchool class as you wish.
The general form of the java statement with new operator looks like: -
Thus a new instance of a software object gets created according to the definition
found in the class <class-name>. The class-name is used as a user defined data type. The
new operator reserves a chunk of memory space that will be required to store that object
during execution time.
A class defines a user defined data type (with a number of instance variables
and methods) that can be used as a template for creating many objects.
Suppose the ICSE board wants to print out the details of all the schools sending
students for the final examinations. A Java program using the Class manySchool -- can
create school objects giving names as school_1, school_2, ..... school_N and by calling the
method as school_1.displayDetails(), ...., school_N.displayDetails() details of all N-
schools can be found out. This is the beauty of an OOP language like Java.
Java has another advantage, which other OOP languages are not having. It is
platform independent – that means you can run the same Java program on any computer
platform irrespective of the hardware, operating system and network protocol differences.
Discussion about this aspect has already been made in chapter-0.
/**
* Constructor for objects of the class manySchool
*/
public manySchool()
{
// Initialize instance variable
name = "null";
}
/**
* methods used in the class
*/
public void setName(String actualName )
{
name = actualName;
}
public void displayName()
{
System.out.println( " School name is : " + name);
}
}
Please note that void is a return type. The setName() method has one String type input
parameter and displayName() has no parameter to pass.
Using BlueJ run this program to create as many school objects you like by clicking
repeatedly new manySchool(), set the school names, one by one, by calling setName()
method. Check the name of a particular school-object by calling the displayName()
method. (See Picture 1.3)
Picture 1.3 Creating many school objects from manySchool class
1.2.2 Constructors
How can you initialize the variables in a class each time an instance gets created?
Java allows objects to initialize themselves when they are created. Using one or more
constructor(s) [see Example 1.3] initialization is performed. A programmer can either
define constructor(s) according to his/her requirements of initialization or can depend on the
default constructor. For the time being we will depend on the default constructor and the
detailed discussions on user defined constructors will be made in chapter-3.
You have seen that the new operator can create an object school_1 from the class
School ---
What actually happens is that the constructor – School () creates the school_1
object. The School () constructor may be a default one if it is not defined explicitly. The
default constructor initializes all instance variables (like name, address, etc. .....) with null
or zero values. For a simple class, the default constructor may be sufficient; but for more
complex and sophisticated applications, a programmer is forced to define one or more
constructors for the class being defined.
A java program is a collection of one or more Classes out of which one class
must contain the main() method. Program execution starts with that class where the main()
method is present. Therefore a single class java program must contain the main() method
besides any other method(s) required to be included.
In a program one can easily include any predefined class or classes lying stored in the Java
Library. Such reuse of Class(es) helps a programmer in minimizing program
development time and taking burden of extra coding.
For example, you have already taken help of a System Class from java library. To
display any result or text message, on the VDU-screen or terminal window, you use the
statement
System.out.println (.........................);
A library package is a collection of many commonly used Classes, which are often
required by java programmers. The most essential support package, java.lang, is got to be
included with any java program. It includes classes like System, Compiler, String, Runtime,
etc. That is why the java.lang package gets automatically included with any java program.
Being a member of the java.lang package, Math classes [which contain functions like – sin(),
cos(), tan(), exp(), log(), sqrt(), etc.] are implicitly included with any java program you load
for execution.
There are quite a few other useful packages, like java.util containing utility classes,
java.io containing input/output classes, etc., which are although present within the Java
Development Kit, but are not automatically included with java programs. Except java.lang
package all other packages are to be imported explicitly by adding import statements like ---
import java.io.*;
import java.util.*;
...... ......
/**
* Constructor for objects of class Sin
*/
public Sin(double ang)
{
// initialise instance variables
deg = ang;
}
/**
* An example of a method using Math Library
*/
public void sinMethod()
{
double rad = deg*22/(7*180);
double result = Math.sin(rad);
System.out.println (" sin of the angle =" + result);
}
}
Execute this program to find out the sine values of different angles fed as a
constructor parameter.
Points To Ponder
* Different attribute values (like name, address, age, etc.) [used as instance
variables] differentiate one object from another. Attributes are also called state
members.
*Member Functions or Methods of a Class give descriptions of the behaviour of
any object belonging to that Class.
• An object of one class can interact with the objects of other classes by passing
messages.
• A class with a main () method can start execution without creation of any object
out of it first.
• A class not having a main () method cannot start functioning unless an object
instance of it is created first.
Important Questions
• How can one define a method or member function in a Class? How is main ()
method defined?
Note: In a class data type of every attribute and the return type of every function or
method must be specified explicitly. When do you specify void as a return type?
In our day to day activities we make use of numeric values to specify numbers or
quantities. Similarly, to write names, addresses, etc. we use alphabetic symbols and any
alphanumeric combinations.
Again, numeric values may be of Integer type (like 34,95, 8, .....) or float type ( like
3.14, 229.65372, ......). Similarly, alphabetic symbols use characters (like ‘y,’ ‘n’, ‘t’, ‘f’,
‘x’, ‘y’, ‘z’........); and the String type uses character combinations (like “Amit”, “
Modern School” , “ 37/1-B Park Street”, ........etc).
Examples – boolean b;
b = true;
All values, shown above, are the examples of simple or primitive data types. Java
can handle any data also as objects belonging to some wrapper classes like Integer, Float,
Boolean, Long, Double, etc. Java provides classes for each of the simple data types. For
example, Float objects can be constructed with values of simple data type float or double.
Note the convention – all wrapper class names start with the Capital letters.
Every string in Java is an object created out of the class String (which remains
defined in the java.lang package). String constants are actually String objects.
---- is a Java statement which creates a string constant [ mystring] using character values
[ placed within “ ........”]. Remember, once a string object is created in a java program its
contents cannot be altered. Moreover, once a string object gets defined it can be used at any
place where a string is allowed. For example
You are familiar with the + operator used to add two numeric values. String Class is
capable of adding sub-strings into a longer string (technically known as concatenation) as
shown above. String Class also contains methods like equals (....), length (...), charAt(....),
etc. We will discuss about them in some later chapter.
// operands
double x;
double y;
// Constructor
/**
* examples of different operations
*/
}
}
If you run this program with x = 12.0 and y = 3.0 the output that you will see is shown
below:
value of x * y = 36.0
Inverse of x is = 0.08333333333333333
Besides arithmetic operators, Java allows Bitwise Operators [NOT, AND, OR,
XOR, shift Right, etc. ], Relational Operators [ (= =)equal to, ( !=) not equal to, (>) greater
than, (<) less than, etc.], Boolean Operators [ AND,OR, XOR, etc. ], the Assignment
operator [ variable = expression], etc. We will discuss about them in details afterwards.
/**
* Write a description of the class Area here.
*
* @author (A.M.ghosh)
* @version (7.3.2005)
*/
public class Area
{
int length, width; // attributes
The class Area knows how to calculate the area of a rectangle when its length and
width are specified. The AreaDemo class utilizes the Area’s cover () method to find out the
covered area of a rectangle. The static main () method of AreaDemo class controls all
activities concerned with the area calculation project making it self-start.
Enter and run example -1.6 and check the output values.
If a Java project needs many classes for interactions, there must have one class to
control all interacting objects. That computation controlling class must contain the static
main (.. ) method which has a constructional look like –
The meaning of each key word of the main (...) line will not be explained here
because that would demand a detailed understanding of Java’s approach. Just be satisfied
with the remarks given here.
The keyword public indicates that this particular member (method here) may be
accessed by any external class codes.
The keyword static allows java’s interpreter to call the main () method without
creating any particular object instance of that class.
The key word void tells the java’s compiler that this main () method does not return
any value as output. Of course, main (..) method is quite capable of returning values, if
situation demands.
Note: If you work with BlueJ environment, simple main () can be used instead of main
(String args []). For text based command interactions, main (String args []) construct is got
to be used always.
Carefully study the example-1.6. In that program two classes, namely Area and
AreaDemo, have been defined. Identify the message passing statements used there.
Objects can interact between themselves by passing messages. Such message
interactions invoke functions, which ultimately do the computational work.
The class containing the main () method generates all objects and controls the
messages required to perform the computational activities – like assignment of values to the
variables, invoking appropriate methods and printing results as per job requirements.
Learn by Doing: --
(1) Study carefully the example-1.6 and try to detect the presence of messages there.
(2) Create a project with more than one classes defined within it. Control your
program by the class which contains the main ( ) method.
User defined methods may have zero, one or more parameters to pass according to
the activities taking place within the method body.
Parameters can help a method to operate on a variety of data. For example --
Here by passing any value of i, one can get its square value. Now square can act as
a general-purpose method.
Java statements are like English sentences. A statement forms a unit of execution.
The statements like assignment (a = 12.5:), decrement (b--; ), method call
[ System.out.println ( “ The value of a is “ + a); ] , declaration ( int x = 25;) are
called expression statements. In a java program, such statements are executed in a
sequential order.
Program execution can be diverted from one sequence path to another (Fig-
1.4) looking at some condition. If the condition gets satisfied then the path1
statement(s) will be executed, else path2 statement(s) will be executed.
condition
else
Fig-1.4 If-else then
Construct
Path1 Path2
if (condition) statement1;
else statement2;
Java allows a sequence of nested ifs [if-else-if ladder] whose construct has the look like
this :--
if (condition1) statement_group1;
else if (condition2) statement_group2;
else if (condition3) statement_group3;
|
|
else
statement_group_default;
Such if statements are executed from the top down. As soon as one of the conditions
gets satisfied, the associated statement_group is executed and the rest of the ladder is
bypassed. The final else acts as a default statements.
Iteration means repeating a procedure again and again. That means, for a group of
statements, execution will start from the top and reaching the bottom-most statement the
control will loop back again to the top. Such looping can continue for a fixed number of
times or will go on continuing until a pre-defined condition gets satisfied.
1.6.1 Known and Unknown Number of Iterations
print Result;
result = 0;
for (int i=0; i <10; i++) {
result = result + number[i];
}
System.out.println ( “ Sum of 10 numbers = “ + result);
If only one statement is repeated, there is no need to use curly braces. For a fixed number of
iterations, for-loop is most suitable.
The while loop is most popular in Java. It has the general form of:-
while( condition) {
body of the loop
}
The body of the loop will be executed as long as the condition expression remains true. This
while-do construct is used when the condition is checked first before the loop body gets
executed. If condition is found false, the body will remain unexecuted. If you want to ensure
the execution of the loop body at least once, then you have to make use of the do-while
construct:--
do {
body of the loop
} while (condition);
Further discussions with applications of such control statements will be made in chapter-7.
1.7 Conclusions
This chapter has tried to give an “Elementary concept of Objects and Classes “ that
forms the foundation of OOP. The concept of physical objects, and the attributes by which
they can be differentiated has been explained first. Software objects in Object Oriented
Programming are created as replica of physical objects so that object interaction can imitate
the real-life activities. Since physical objects are capable of doing some work, so software
objects are also made to behave similarly with the added methods or functions. Thus a
special composite data type – called class, which encapsulates both attributes and methods –
is framed to use for OOP languages.
Java supports simple data types like int, float, etc.; complex data types like objects
belonging to the wrapper classes of the types Integer, Float, etc. and User Defined Data
Types like class/objects. The importance of String class is also described briefly.
The importance of library classes in a java program has been explained. The
special role that the main () method of a class is supposed to play has been shown with
appropriate examples.
Creation of objects out of defined classes and interactions allowed between them
by passing messages fulfil the goal of computation. This concept has been demonstrated by
considering a real-life bank transaction example.