You are on page 1of 20

Chapter 2:

Class as the Basis of all Computation

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.

2.1 Derived Objects ( from a Class) for Computation

A java programmer is supposed to define one or many classes according to the


application requirements. Objects are created from those defined classes. Therefore, all
objects in a program are derived from some pre-defined classes, either programmer-defined
or java library-defined.

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.

2.1.1 Defining a class

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.

/** Simple Addition


* Write a description of class Add here.
*
* @author (A.M.Ghosh)
* @version (20-4-2005)
*/
public class Add
{
// instance variables
double x;
double y;

/**
* 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

Example – 2.1 Definition of a class Add without main () method.

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.

Execute example-2.1 with different object instances and input values.

2.1.2 Defining another class Student

Suppose Pradip Bhatt is a student of class X of your school. He can be created


software-wise by a class named say StudentX. Pradip’s record will be an object of that class
like any other student belonging to class-X.

How is the class StudentX can be defined? Of course, by specifying a group of


attributes like – name, father_name, address, date_of_birth, school_name, ..... and by
including along with those a group of functions like – setSchool(), setName() ........,
getDetails(), getSchooName(), .......etc.

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

public class StudentX


{
String name;
String father_name;
String address;
String date_of_birth;
int year_admission;
// This is a constructor with parameters
StudentX(String sn, String fn, String stadd, String dtbirth, int ya ) {
name = sn;
father_name = fn;
address = stadd;
date_of_birth = dtbirth;
year_admission = ya;
}
public void getDetails() { // method getDetails() starts here
System.out.println (" Student Name is : " + name);
System.out.println(" Father's Name is : " + father_name);
System.out.println (" Date of birth is : " + date_of_birth);
System.out.println(" Student Address is : " + address);
System.out.println (" Year of Admission : " + year_admission);
} // method ends here
}

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.

2.2 Composite Data type

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.

Actually date_of_birth, is a variable of composite data type because, instead of a single


value, three values -- one each for date, month, and year -- are required to compose a date-
of-birth. Similarly, separate data values for street, city, state, pincode, etc. are required to
fully specify an address. To tackle such composite data types one can make use of user-
defined classes (like AnyDate and Address as shown below) out of which many date and
address objects can be created according to the application requirements. Examples of such
user-defined classes are shown below.

Example 2.3 AnyDate class to create date objects in composite form

public class AnyDate


{ // instance variables
public int day;
public int month;
public int year;
// a constructor
public AnyDate()
{
day =0;
month =0;
year =0; }
// methods
public void setdate(int d, int m, int y )
{
day = d;
month = m;
year = y;
}
public void getdate ()
{
System.out.println( " The date set to : " +day+ "-" + month+"-"+year);
}
}

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

import java.util.*; // included for use of the Date class

public class DateDemo {


public static void main() {
// use of Date composite data type
Date today = new Date(); // one date object is created

System.out.println(" The date is : " + today);


}
}
Picture 2.2

The output of this program has been shown in Picture 2.2.

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.

Example 2.5 class Address (as a user defined data type)


public class Address
{ public String name;
private String street;
private String city;
private String state;
private int pin;

/**
* 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

2.3 Data Type Compatibility


Java is a strongly typed language, which means every variable has a type, every
expression has a type, and every type should be properly defined. Moreover, all assignments
are checked for type compatibility. Java compiler checks all expressions and parameters to
ensure that respective types are compatible. Errors are raised whenever any types mismatch
arises.
In chapter-1, an introduction to simple data types like byte, short, int, long, char, float,
double and boolean has been given. Now, through examples, let us now try to understand where
and how they are to be used in a java program to ensure type compatibility.

Example 2.6 Use of type -- double

public class CircleArea


{
public static void main() {
double pi, radius, area;
radius = 12.34;
pi = 3.1416;
area = pi * radius * radius;
System.out.println( " Circle Area is = " + area);
}
}

Example 2.7 Use of types --- short, int and long

public class ShortLong


{
public static void main() {
short days;
int minutes;
long seconds;
days = 7;
minutes = days * 24 * 60;
seconds = minutes * minutes;
System.out.println(" 7 days = " + minutes + " minutes ");
System.out.println( " 7 days = " + seconds + " seconds");
}
}

Example 2.8 Use of Boolean variables

public class Logic


{
public static void main(){
boolean a, b;
a= true;
b = false;
boolean c = a | b; // OR operation
boolean d = a & b; // AND operation
System.out.println(" a OR b is :" + c +" a AND b is : " + d);
}
}

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.

Example 2.9 Use of Type – char

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);
}
}

By running this program you will see the output –

65 represents the character: A


Next character will be: B

Note: What idea do you gather from this simple example?

2.4 Declaration and Initialization of Variables

Remember that all variables must be declared before they can be used.

Examples of variable declarations : ---

int a, b, c; // only variables are declared , not initialized


int d= 25, e = 76, f = 17; // variables are declared and initialized
float g, h; // float or double – which one has higher precision?
double j = 4.0, k = 6.7;

2.4.1 Dynamic Initialization:


Java allows variables to be initialized dynamically as shown below: --

double m = Math.sqrt( j*j + k*k); // m is initialized dynamically


// sqrt(..) is a method of class Math
// where j and k must be declared as double
because return type is double
** Check --- what compiler will do if you use float instead of double for the
variable m

2.4.2 The Scope and Lifetime of a Variable

In a class, one or more blocks can exist. What is a block?

A block starts with { //- - - - - - - - - - - - - - - block starts here


Variables;
Expressions or nested block(s);
} // - - - - - - - - - - - - block ends here

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?

A class may be taken as a combination of blocks as shown in Fig-2.1.

class <ClassName> { // start of class


public static void main() {
// start of main block-1

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

Fig- 2.1 A class structured as a combination of blocks

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.

Example 2.10 Scope of Variables

class ScopeDemo {
public static void main () {
// scope of main-block starts here
int a , b;
a = 2;
b = 3;

void methodx() { // another block scope starts here


float x =12.3;
System.out.println( “value of x =”+x+” value of a =”+ a)
} // scope of x ends here

System.out.println (“Value of x :” +x); // Error will be raised


// being outside scope of inner block
// methodx() is nested within main() block
}

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.

2.5 Type conversion and Casting

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

new-type = ( target-type) old-type

Example 2.11 Casting of Different Data Types

public class CastingDemo


{
public static void main()

{ byte b; // modulo 256 --byte range


int i =321;
double d = 1425.7654327654312;

System.out.println("value of Int is " + i


+" value of double is " + d);
float f;
b = (byte) i; ----// casting int to byte
System.out.println ("byte casting gives:" + b);
i = (int) d; ---// casting double to int
System.out.println (" integer casting of double gives:" + i);
f = (float) d; ---// casting double to float
System.out.println (" float casting of double gives:" + f);
}
}

For practical purposes, double precision variables can be printed in a short form using
the method of casting.

2.6 Encapsulation

As mentioned earlier, an object can be described as a collection of attributes and


methods declared and defined within the class to which it belongs. Methods include action
codes, which can be called by other interacting objects without knowing their inner details.

Encapsulation is a mechanism by which attributes and methods remains bound


with the definition of a class and can keep both safe from external interference and
misuse. It can be thought of as a protective wrapper that can prevent access of both data
and codes placed within the boundary of a class or an object. Access is possible only
through a well-defined interface. Thus data and function or method members (containing
codes) can remain well protected.
Access to a method or a variable declared in a class, can be controlled by marking
each one as private or public. Any external code or object can access the public members, if
needed, but private members can be accessed only by that program code which is a member
of the respective class. A programmer should carefully choose the public interface of a class
so that hiding of inner details is not jeopardized.

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.

By default, that is when private or public is not explicitly mentioned, members of a


class are regarded as public within its own package boundary, but cannot be accessed by any
codes outside that package. Further details on encapsulation and package scope will be
discussed in chapter-9.

2.7 Member Variables & Member Methods of a Class

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

variable-name = class_name.method_name ( parameters if any ).

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.

Example-2.12 A class Cos takes help of the Library class -- Math

import java.lang.*; /*importing library package where Math classes


* iareavailable */
public class Cos
{
// instance variable

double deg; // input variable

/**
* 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
*/

public void cosMethod()


{
double rad = deg*22/(7*180);
double result = Math.cos(rad); // access Interface
System.out.println (" cos of the angle =" + result);
}
}

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.

Example 2.13 A CalDemo program with embedded operands

public class CalDemo


{public static void main(String args[]) // with main() method
{
// with fixed – operands
double x = 10.35;
double y = 20.95;

/** creating objects from the defined


* classes Add, Sub, Sin, Log, etc....
*/
Add plus = new Add(x,y); // object plus created from Add class
Sub minus = new Sub(x,y); // object minus created from Sub class
Mult product = new Mult(x,y); // object product created from Mult class
Div divide = new Div(x,y); // object divide created from Div class
Power topow = new Power(x,y); // Power class reuse Math class pow() method
Sin angsin = new Sin(x); // Sin class reuse Math class sin() method
Log logval =new Log(y); // Log class reuse Math class log() method
Inv invert = new Inv(x); // object invert created from Inv class
Cos angcos = new Cos(x); // Cos class reuse Math class cos() method

/**
* 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

*/ To perform calculations with any two input values


* one parametric Constructor to accept two operands */

public class NewCalDemo


{

// 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);

}
}

Picture 2.4 Output of the Calculator Project

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

2.8 Importance of static Method

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.

When a method is declared as static, several restrictions get imposed:


i) a static method can call another static method only;
ii) it should access only static data;
iii) this or super references cannot be applied.
iv) It is illegal to refer to any instance variable inside a static method.
v) You can call a static method from outside using dot(.) operator in the form
classname.method()
----- where classman is the name of the class where static method is declared.

In the same way, a static variable can also be accessed by using dot (.)
operator [ classname.dataname] by any code outside that class.

2.9 Importance of main () Method

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

2.9.1 Command-Line Arguments

In two different ways you can write the main () method in a class --- simply
by using
public static void main() { .......... } // for BlueJ environment only

or keeping a provision to pass some command-line arguments while invoking


the main () method, by using ---

public static void main( String args[]) { ........ } // for any other environment

A command line argument(s) become(s) essentially required when text-based


program execution is done under DOS or Linux command prompt. As text-window
prompt can accept only string input s (not mouse click), so (String args[]) is got to be
used while defining the main-method, otherwise compilation error may occur.

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.

You might also like