Professional Documents
Culture Documents
2.0 Introduction
From earlier discussions you have understood that many software objects can be
created from a defined class which encapsulates a group of attributes (values of which
will be different for different objects) and a number of methods or functions (which stand
for the operations that all objects of that class are capable of doing). Such methods actually
control the behaviour of the objects being created. Many classes can create many varieties of
objects, which can interact amongst themselves by passing messages as per computational
requirements.
The data members or variables, defined within a Class, are called instant variables.
Methods include codes to manipulate those variables. Data and methods, included in a
class, are collectively called members of that class. Therefore, every class has one or more
data members and one or more method members. Java classes can be defined without
having a main () method within it. If a project consists of many classes, then only one class
should contain the main () method. Of course, a project using a single class should contain
the main () method. The class containing the main () method is supposed to control the
entire computational activities taking help of objects created out of other defined classes.
Now two questions may arise – one, how to specify data members with appropriate
data types; and two, how to define different methods or functions so that objects can use
them easily and correctly. Programmers must have a clear idea about the java’s data types.
A detailed discussion on the primitive data types and composite data types will be
made here first. Choice of appropriate data types for fulfillment of users’ requirements is
very important. Improper choice of data types for members may give rise to compilation
errors. Some hints on how to choose correct data types, will be given so that compile-time
errors can be avoided.
One to one mapping of real-life objects of the application domain onto software
objects of the programming domain is quite possible and often done in a java program.
The way a real-life object with its state and behaviour is described can be copied in toto to
describe a software object. A java programmer can create good many similar objects from a
single class definition. Therefore, a class definition should include all distinguishing
attributes and common methods by which similar real-life objects can be described.
A software object itself can be regarded as a composite data type because it encapsulates
many instance variables (of different data types) and a number of functions or methods
(each one with zero, one or more input parameters and a return data type). The importance
of the correct choice of data types while defining a class can be made clear by taking help of
some concrete examples.
BlueJ window helps you defining a new class very easily. Enter a project name
and the class name within that project -- a pre-defined template [similar to Picture 0.3]
appears on your VDU screen for editing.
The editor template shows how and where to place the class names, instant
variables, constructor, methods, etc. It also shows how to put documentation comments
within a program using multi-line comments within /* ...............*/ and single line
comments using //............... Use of such comments can make a program self documented
for users who are supposed to understand and modify it as and when necessary.
This template has not included any main () method, so its execution will not be
possible without creation of its object instance first. As mentioned earlier, if a class includes
a main () method, execution of that class can start by itself without creating any object
instance. Try it yourself and gather experience.
Using the BlueJ editor template a simple class Add, which is capable of adding any
two given numbers, has been defined as shown in example-2.1.
/**
* Constructor for objects of class Add
*/
public Add( double a, double b)
{
x = a;
y = b;
} // end of Constructor
/**
* method of addition
*/
public double addMethod()
{
// put your code here
return x + y;
} // end of Method
} //end of Class
Data types of instance variables x and y have been chosen as double so that any
number with highest possible precision can be taken care of by the class. Using the
constructor you can input and initialize any two numbers that are going to be added. Since
Add has no main () method, you have to create an object of class Add first (say Add_1)
which will ask for two numbers which you have to enter. Clicking on the created object,
invoke the addMethod() to obtain the output result.
Name, father_name, school_name ......, etc are the variables which can accept
String types data because their values are normally specified by an array of characters
like “ Pradip Bhatt.” [don’t forget to use the double quotes at both ends], etc. By taking help
of a suitable parameterized constructor to pass attribute values as parameters (like name,
father_name, etc.) -- necessary information for different students can be collected by a
computer program. A sample such class definition is shown in example –2.2.
Example 2.2 Definition of class StudentX
Picture 2.1
By using this program in BlueJ environment you can go on creating many student
objects and their details can be displayed on VDU and stored in a file for keeping records, if
you so wish. Picture 2.3 shows the BlueJ: Create Object window for collecting student-
information as parameters of the class constructor.
[Assignment: --Try to keep records of all your friends defining a class Friend.]
In the getDetails() method of the class StudentX, the return type has been shown as
void because the method does not return any data value for further use but takes all actions
inside the method body, like printing student’s details on the VDU screen.
In example- 2.2, the data types of address, date_of_birth, etc were chosen as single
String types. In simple applications, that can serve the purpose. If an application just wants
to know the street name only of the address attribute or the month only of the date_of_birth
attribute, then such use of single String type will not serve the purpose.
Enter, compile and run this program in BlueJ and see how three integer variables
compose the composite date variable.
It may not be out of place to mention that java.util package contains a class called
Date from which the present dates and time object can be created. How easily you can use
it to print the current date and time is shown in Example 2.4.
Example 2.4 Use of the Date class present in the java.util package
Note: To use the library class Date, which is present in the java.util package, you
have to include the statement -- import java.util.*; in your program.
Moreover, the DateDemo class has used main () method. So its running is possible
without creation of any object.
/**
* Constructor for objects of class Address
*/
public Address( String nam, String str, String cty, String st, int p)
{
name = nam;
street = str;
city = cty;
state = st;
pin = p;
}
public void getName()
{
System.out.println (name);
}
public void getAddress()
{
System.out.println( street);
System.out.println ( city);
System.out.println (state);
System.out.println (pin);
}
}
Note: Observe the use of private and public access control scheme.
Create as many name-address objects as you like using this program and store it in a
file for your future use. Thus you can easily create a name -address database for look up.
Convention :
• Class name starts with a capital letter -- like Student, Address
• Objects are created with names starting with small letters -- like
student1, student2, .......... ,studentN, address1, .... addressM, etc
Note: Since variables a and b are declared as boolean, logical operations like OR, AND,
etc will only be allowed by the java compiler, which will raise error flags if you try to perform
any arithmetic operations with them.
class Chardemo() {
public static void main () {
char ch1, ch2;
ch1 = 65;
System.out.println(" 65 represents the character : " + ch1);
ch2 = ++ch1;
System.out.println( " Next character will be : " + ch2);
}
}
Remember that all variables must be declared before they can be used.
A class starts with a {bracket and ends with a} bracket. Similarly, every method
starts with a {bracket and also ends with a} bracket. So every method can be regarded
as a block within a class. Declaration of variables, whenever required is also allowed
within a method. What will be the scope and lifetime of such local variables declared
within different blocks?
instance variable1;
instance variable2;
method()
{ // start of inner block-2
variable3;
variable4;
other codes;
............
} // end of inner block-2
} // end of main block-1
} // end of class
In a class, the main () method may contain another method inside as shown in Fig-
2.1. Java allows declaration of both global and local variables in a class.
A block {------} defines a scope for the variables declared within that block. The
scope determines the visibility of variables by other parts of a program. In java, there
are two scopes – class scope and method scope. Method parameters are also included
within the method’s scope.
class ScopeDemo {
public static void main () {
// scope of main-block starts here
int a , b;
a = 2;
b = 3;
Remember: a variable declared in the outer block remains visible within the inner
block but the reverse is not true. That is, in example 2.10, the main () method will not
recognize variable x, although methodx() will recognize all the variables a, b, and x.
It is possible to assign a variable of one type into a variable of another type provided
the two types are compatible. For example, declared int type variable can be converted to a
long type variable and that conversion will take place automatically. But many types are not
compatible, like double to float or double to byte. In that case we have to make use of
casting which performs explicit conversion between incompatible types. Example 2.11
shows how forceful conversion is possible using the method of casting.
To enforce a conversion between two incompatible types, we have to write an
expression in the form of
For practical purposes, double precision variables can be printed in a short form using
the method of casting.
2.6 Encapsulation
Encapsulation links data with the codes, which manipulate them. A class can be
regarded as a black box, which can be used by external codes but should be prevented from
tampering. The main () method is always used with public specifier – why? Because, it is to
be called by the Java run-time program.
A class can be defined with a good number of instance variables and methods packed
together. Instance variables and function parameters may be of simple data types or
composite data types, even be of object type. Instance variables of a class are normally
accessed by taking help of appropriate methods or functions lying defined within the same
class. Java codes can make use of the function output, for further processing, taking help of a
dot-expression --
Suppose a class named Cos is defined to find out the cosine of an angle. The angle is
passed as an input parameter. The method by which cosine value can be found out is already
available in the Math class defined in the java.lang package. That package is got to be imported
and used while defining the Cos class as shown in example-2.12.
/**
* Constructor for objects of class Cos */
public Cos(double ang)
{
// initialise instance variable with input data from console
deg = ang;
}
/**
* An example of a method utilizing Math.cos() library method
*/
Within the Math classes of the java.util package, the cos-method of finding the
cosine-value for a specified angle, expressed in radian, remains defined. Through the
interface Math.cos( ) – just the output value is obtained. The user’s Cos class just utilizes
the code without knowing its inner details.
From the class Cos, you can go on creating objects like cos10, cos20, cos30, cos45,
... etc and find out the respective values by calling the cosMethod() of the created objects
one by one.
In the same way you can create classes to compute values of different mathematical
functions like tan, log, pow, etc. ... ... and use them in your program according to
requirements.
You can easily create a software package Calculator by combining many such
mathematical classes as shown in example-2.13.
/**
* results obtained from different calculations
*/
double presult = plus.addMethod();
System.out.println(" value of x+y= " + presult);
double mresult = minus.subMethod();
System.out.println(" value of x-y= " + mresult);
double into = product.multMethod();
System.out.println(" value of x * y = " + into);
double dresult = divide.divMethod();
System.out.println( "value of x/y = " + dresult);
angsin.sinMethod();
angcos.cosMethod();
logval.logMethod();
double invres = invert.invMethod();
System.out.println(" Inverse of x is = " + invres);
}
}
In example-2.13, carefully observe how objects are created by the reserve word “new”
from the classes defined in a calculator project package (Picture 2.3).
CalDemo class integrates all the objects created out of different classes [Add, Sub, ..., Sin, Cos,
..., Log, etc.] present in the project package. So a large program can be developed easily by
defining component classes first and then combining them together by another class [here
CalDemo] which has a main () method to self start and control execution of a program
combining all the concerned classes.
The only drawback of example-2.13 is that the program can take care of only two
fixed operands specified as instance variables. The flexibility of the program is lost here. To
ensure flexibility, a user must be able to pass any desired values as operands. To achieve that
goal, CalDemo class is modified by removing the main () method from example-2.13 and
adding a parametric constructor and a separate compute() method as shown in
example-2.14 (see Picture 2.3).
Example- 2.14 Modified CalDemo class without main () method
// any operands
double x;
double y;
// parametric constructor
public NewCalDemo( double a, double b)
{ x = a;
y = b;
}
/** creating objects from the defined
* classes Add, Sub, etc....
*/
public void compute() {
Add plus = new Add(x,y);
Sub minus = new Sub(x,y);
Mult product = new Mult(x,y);
Div divide = new Div(x,y);
Power topow = new Power(x,y);
Sin angsin = new Sin(x); // Picture 2.3 Defined Classes in the Calculator Package
Log logval =new Log(y);
Inv invert = new Inv(x);
Cos angcos = new Cos(x);
/**
* different operations by calling appropriate methods
*/
double presult = plus.addMethod();
System.out.println(" value of x+y= " + presult);
double mresult = minus.subMethod();
System.out.println(" value of x-y= " + mresult);
double into = product.multMethod();
System.out.println(" value of x * y = " + into);
double dresult = divide.divMethod();
System.out.println( "value of x/y = " + dresult);
angsin.sinMethod();
angcos.cosMethod();
logval.logMethod();
double invres = invert.invMethod();
System.out.println(" Inverse of x is = " + invres);
}
}
To run the program example-2.14, you have to create an object first by calling the
constructor by passing two numeric values as operands. The computed results will be
obtained when you invoke the compute () method of that object (see Picture 2.4). Try to run
the program by creating different objects having different parametric values.
Carefully study the Power operator class (Picture 2.5) details [where a Math class of
the java.lang.* library has been utilized] defined in the Calculator package.
Picture 2.5 Power Class details of the Calculator Package
Any data member or method member of a class can be declared as static. When you
wish to declare any member that should remain independent of any object instance, that
particular member must be tagged as static. The main () method is always declared as
static so that execution can start without creation of any object first (to make it object
independence). To start a multi-class java program by itself, the controlling one must
include the main() method [ like CalDemo or NeWCalDemo class (ref. Picture 2.3)].
Observe the class relationships shown by the dotted lines.
When any data member is declared as static, it becomes a global variable, which
means that all object instances will share the same variable with the specified value, if
declared.
In the same way, a static variable can also be accessed by using dot (.)
operator [ classname.dataname] by any code outside that class.
By this time you have been able to realize the importance of the static main () method
in a class. If you like to make a java program self-starting, you must have to define a class
with the main () method where various objects from other classes can be created and used for
computational requirements [see example-2.14].
In two different ways you can write the main () method in a class --- simply
by using
public static void main() { .......... } // for BlueJ environment only
public static void main( String args[]) { ........ } // for any other environment
If you run your program in BlueJ environment, you can choose any form you
like, but the generalized form, that is main (String args[]), keeps the provision of
argument passing and mostly preferred by java programmers.
2.10 Conclusions
This chapter has dealt with the different aspects of data types used for instant
variables and method parameters. Java is a strongly typed language and even “void” type is
got to be used when a method is not supposed to return any value.
The scope and casting of data variables declared at different portions of a program
have also been discussed citing appropriate examples. It has been clearly demonstrated how
to declare variables, how to construct methods with scope variables, how to use constructors
with parameters, how to import library classes in a user defined class, how to create objects
of respective class types, etc. The importance of the main () method – with and without
String arguments-- has also been explained.
In BlueJ environment you can test individual classes defined for a project, one–by-
one, and then finally test the entire integrated program by defining a self-starting execution
control class which must include the main () method. This makes the program development
process much simpler, modular and easier to detect errors.