F BCA Java Programming
F BCA Java Programming
Introduction to Java
o History of Java
o Features ofJava
o Java Compiler andInterpreter
o JVM (Java VirtualMachine)
o GarbageCollection
o Structure of JavaProgram
1 1-39
o Writing Compiling and Executing SimpleJava Program
o Data Types inJava
o WrapperClasses
o Java NamingConventions
o Input / Output inJava
o Control Structures inJava
o Arrays inJava
Concurrent Programming
o Concept ofThreads
o Lifecycle ofThreads
o CreatingThreads
4 127-139
o ThreadClass
o RunnableInterface
o Thread Class Vs. RunnableInterface
o Introduction to ThreadSynchronization
Java Input/Output
o ConceptStreams
5 140-152
o Types ofStreams
o BufferedStreams
Abbreviations
References
UNIT - 1
INTRODUCTION TO JAVA
NOTES
Ejcrvgt"Qdlgevkxgu"
To understand –
o Development of Java
o How Java is different than other Programming Languages
o Java Compilation Process and JVM
o Writing Procedure Oriented Programs in Java
o Using Arrays in Java
Jkuvqt{"qh"Lcxc
James Gosling is the person who designed the language in 1991 along with
his team at Sun Microsystems. Initially, the team was developing language to
program processor-controlled home appliances. Controllers were wide in variety
and so language was developed with a feature of ‘not controller specific’. Home
appliances like a set-top box, washing machines, fridge, microwave and many
more. The first version of Java was used to write these controller programs.
During 1994, Gosling realized the need to use the
language for network programming. In 1995 it was
introduced as a network programming language and the
Netscape was the first browser to run java programs.
Nowadays Java is preferred for the development
of robust software. It has become so popular because of
its features, which we are going to discuss in
forthcoming chapters. Though Java is a relatively new
programming language, it is accepted and widely used
for various applications. And as an introduction of new
concepts, makes it more powerful.
How it was named ‘Java’?
Why Logo is ‘Coffee Cup, Saucer, and Steam’?
Every new invention is to be named for its recognition. The developer team
of java was also looking for a suitable name for their new invention. The
development team was named ‘Green Team’ and hence name suggested for the
language was 'Oak'. But afterward, it was learned a language with the same name
was already existing. So now the team was worried about finding a new name.
By making an acronym of team member names they formed a new name as
JAVA (James gosling, Arthur, Van Hoff, Andy Bechtolsheim). Coincidently it is
the name of an island that is famous for coffee beans and all were a fan of it. At
Introduction to Java 1
Qdlgev"Qtkgpvgf"Rtqitcookpi"Ncpiwcig
Java is considered to be pure Object Oriented Language, as everything in
java is an Object. Objective of Object Oriented Programming paradigm is to
provide security to data from unintended processes. Object is a basic entity in
OOP which encapsulates data and processes together.
As an OOP language, it also supports all basic concepts of OOP.
Applications developed using Java can be easily extended or upgraded since it
is based on the Object model. This feature makes java applications more durable.
Rncvhqto"Kpfgrgpfgpv"cpf"Kpvgtrtgvgf"Ncpiwcig
Java is more popular because it is platform-independent. Here platform used
to execute an application or service includes hardware and software, hardware
includes a processor, RAM, etc, while software includes an operating system and
other supporting software. Java programs have a feature that makes them
platform-independent.
The compilation process for Java is different than other programming
languages. When compiler translates the High-Level Langage code to machine
level language it adds some feature to code from platform on which it has been
compiled. Hence the compiled code now requires a platform with the same
configuration on which it has been compiled. Hence the compiled version of
application becomes platform dependent though the language is featured with
'platform-independent'. For example, an application written and compiled using
‘c’ language on windows operating system, can be executed on Windows
operating system only, and cannot be executed on machines with Linux or
Ubuntu operating system.
It is not the case with java. Platform creates a foundation that ensures object
code will execute successfully. Unlike many other programming languages
including C and C++, when Java is compiled, it is not compiled into the platform-
specific machine, rather into platform-independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on. Additionally, the interpreter makes the
development process more rapid and analytical since the linking is an incremental
and lightweight process. This makes java ‘Architecture Neutral’ and ‘Portable’.
2 Introduction to Java
Ukorng
Syntaxes used in Java are simple and easy to remember. Moreover, java
maintains uniformity for the implementation of basic OOP concepts. Once
formats used in OOP language are clearly understood it becomes very easy to
write programs.
Java programmers follow programming conventions that should be
followed while writing java programs which helps new programmers to be master
of programming. But if anyone follows these conventions it becomes very easy
for him to read and understand programs written in java. These conventions are
given in upcoming sections.
Tqdwuv
Java makes an effort to eliminate error-prone situations by emphasizing
mainly on compile-time error checking and runtime checking. While compiling
java program all possible future run time errors are estimated and accordingly
program is compiled. It also provides a well defined ‘Exception Handling’
technique for handling run time errors. This helps to handle future errors.
In addition to the full proof compilation process, the Java compiler does not
allow the programmer to have any direct access to memory. The memory
management process is taken care of by JVM while executing the program. The
feature is known as ‘Garbage Collection’.
Ownvkvjtgcfgf
With Java's multithreaded feature it is possible to write programs that can
perform many tasks simultaneously. This design feature allows the developers
to construct interactive applications that can run smoothly.
Lcxc"Eqorkngt"cpf"Kpvgtrtgvgt
Compiler and interpreter are the translators which translate the code written
in High-Level Language to Low-Level Language i.e. machine language.
Programming languages other than java either use Compiler or Interpreter. These
translators translate code once and generate machine code which can be executed
on the target processor.
Java uses compiler as well as interpreter. Java program is compiled in
different stages as compiler and interpreter, both are involved in the process. Java
compiler compiles the program and generates bytecode. The generated bytecode
is interpreted through Java Virtual Machine. This feature of java makes it
different from other languages.
Lcxc"eqorkngt"*lcxce"eqoocpf+"cpf"D{vgeqfg
The source code file of Java program is stored with extension ’.java’. Using Introduction to Java 3
Gzgewvkpi"Lcxc"Rtqitco"vjtqwij"LXO"*lcxc"eqoocpf+
‘Javac’ command only compiles java program to generate bytecode and to
execute the generated bytecode command ‘java’ is used. The command ‘java’
accepts the bytecode file with extension ‘.class’ as an argument. The command
java executes bytecode through JVM.
Before executing bytecode it is interpreted by JVM and then different
resources required to complete execution of bytecode are provided by JVM.
Generally when a compiled code for any language is executed calls processor
for required resources. In the case of java bytecode, JVM calls processor for the
allocation of required resources. After the allocation of proper resources, the
bytecode is executed. In the next point, we discuss about JVM.
LXO"*Lcxc"Xktvwcn"Ocejkpg+
JVM is the feature of java that makes it portable and secure. The diagram
below explains the structure of the JVM. It is a layer working between the
bytecode and the platform on which the program is to be executed. As discussed
earlier bytecode forwards its requirements to JVM. JVM acts as a virtual machine
for bytecode and satisfies all requirements of it.
LXO"Ctejkvgevwtg
The following diagram shows components of JVM and its hierarchies. It
contains a classloader, memory area, execution engine, etc.
Jqy"LXO"ocmgu"Rtqitco"Oqtg"Ugewtg"
The Java VM or Java Virtual Machine resides on the RAM. During
execution, using the class loader the class files are brought on the RAM. The
BYTE code is verified for any security breaches. And consequently, it avoids
direct access to any virus or intruders and makes java programs more secure.
LKV"*Lwuv/Kp/Vkog+"Eqorkncvkqp"
JIT compiler is a part of JVM. Once the class loader loads the classes the
execution engine converts the Bytecode into Native machine code. This is just
in time compiling. It is one of the main reasons why Java is comparatively slow.
JIT works as an interpreter, which interprets bytecode to machine code. Hence
Java is known as the language which is compiled and interpreted.
Ictdcig"Eqnngevkqp
Variables and objects declared in the program being executed occupy
memory. This occupied memory needs to be freed when the variables are not
being used. This freed memory now can be utilized for other purposes. Java
provides an inbuilt facility to free memory occupied by unused objects and
variables. Java is characterized by ‘garbage collector’, who is responsible for the
removal of unused and unreached objects. Unlike other programming languages,
java programmer does not need to worry about the destruction of unnecessary
objects. It is done automatically. Garbage Collector is a Daemon thread that keeps
running in the background. Basically, it frees up the heap memory by destroying
the unnecessary objects. The objects not referenced by any part of the program
are the one which are removed.
For allocating memory block for an object heap memory is used. After a
certain time interval, the garbage collector keeps on checking and destroying
heap for unreachable objects. As the number of objects goes on increasing the
checking time also increases. For this destruction process, some strategy needs to
be applied. The system needs to decide which objects to be kept and which to be
removed. The adopted methodology is called Generational Garbage Collection.
6 Introduction to Java
Uvtwevwtg"qh"lcxc"rtqitco
In this section, we are going to see the basic structure of the java program.
Java is case sensitive language. Java compiler differentiates between capital
letters and small letters and therefore while writing the program in java we have
to be careful about cases of instructions. Maximum syntaxes in java are in small
case. The basic syntax of the java program is like ‘c’ only, as it is developed using
‘c’. The only big difference in ‘c’ and ‘java’ is all instructions in java are written
within the class, as java is a pure object- oriented program. Following syntax
shows how a simple procedure-oriented java program can be written–
/*These are non-executable statements which can denote a block*/ package
<package name>;
import <package name>; class <class name>
{
public static void main(String argv[])
{
//This is also a non-executable statement for single line
//Code to be executed in main()
}
}
Vjg"cdqxg/ikxgp"u{pvcz"hqt"lcxc"rtqitco"ecp"dg"gzrnckpgf"cu"⁄
• The statements which are marked to be non-executable, ignored by the
compiler, are written either within ‘/*…*/’ or if it is a single line it should
start with ‘//’.
• Very first line of java program is declaration of package. It is optional to
write the line. If the program is to be declared as a part of the package,
the program starts with the line. But if the program is not part of any
package, it is not necessary to write the line.
• The next line is ‘import’. The ‘import’ statement is like ‘include’ directive
in ‘c’. It is used to add predefined packages to the program. These
packages are collections of classes and functions and when the developer
wants to use these members from the package, these packages need to Introduction to Java 7
}
} NOTES
By using the above structure a simple welcome program is shown in the
following block – This block shows how a simple java program looks. In the
next subsection, we will see how to save, compile and execute this program.
Ytkvkpi."Eqorknkpi"cpf"Gzgewvkpi"c"Ukorng"Lcxc"Rtqitco
In this section, we are going to see how we can write, compile and execute
a java program. Here we will see three steps for writing and executing Java
program -
i. Writing Source Code –
There are a number of IDEs (Integrated Development Environment)
like ‘eclipse’, ‘NetBeans’ etc. which helps in writing, compiling and
executing Java programs. But here we are going to see how a java
program can be written, compiled and executed using notepad and
command prompt. To write source code using notepad, this is a basic
editor for writing any high-level program. Any java program can be
written in the following steps –
a. Open notepad application.
b. Type your source code.
c. Save your source code file with extension ‘.java’ in your folder.
For example, suppose we type the above program using notepad and
save it with the name ‘[Link]’.
10 Introduction to Java
Fcvc"V{rgu"kp"Lcxc
Before starting the discussion on data types in java, we need to know
something about variables in java. As the name suggests, variables are used to
store data which may vary from one execution to others. The data used in any
program is of two types – constants and variables. Data or value for constant is
known while writing the program, for example, while calculating the area of
circle value of i.e. 3.14. While value for the variable is not known to the
programmer and will be accepted as input from the user, for example, the value
of the radius of the circle for calculating the area of the circle. Here the value of
the radius will go on changing user to user and hence programmer needs to
declare the variable with a proper data type to store its value. Here a programmer
needs to make the decision about the data type of the variable as well as the name
of the variable. About data type, we are going to discuss in detail but before that,
we will discuss rules which has to be followed while assigning a name to a
variable. If any of these rules are not followed then the compiler gives an error,
hence to avoid these errors firstly we will see these rules in detail.
Introduction to Java 11
12 Introduction to Java
NOTES
Lcxc"Rtkokvkxg"Fcvc"V{rgu
As shown in the above figure java avails a wide variety of primitive data
types. These primitive data types are basic building blocks of data manipulation.
These are the most basic data types available in the Java language. Java is a
statically-typed programming language. It means all variables must be declared
before its use. That is why we need to declare the variable's type and name.
There are eight different primitive data types which help the user to
categorize and process different type of data :
• Boolean data type
• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type
Cnn"rtkokvkxg"fcvc"v{rgu"ctg"fkuewuugf"kp"fgvckn0
1. Boolean Data Type
It is used to store Boolean value, ‘true’ / ‘false’. In java, unlike ‘c’, the
return of relational and logical operators is also of type Boolean. The
Introduction to Java 13
Ytcrrgt"Encuugu
Data types known as primitive data types as they cannot be decomposed
further. As well as all basic instructions like input/output, operators, etc. can
process these primitive data types directly.
Introduction to Java 15
Lcxc"Pcokpi"Eqpxgpvkqpu
Below are some naming conventions of java programming language. They
must be followed while developing software in java for good maintenance and
readability of code. For each element of the program in java, some conventions
are defined. While writing any java program if we follow those then it becomes
16 Introduction to Java easy to differentiate between different elements of the program.
Encuugu"cpf"Kpvgthcegu
• Class names and interface names should be a noun.
• The first letter of name should be capital letters and remaining in small
letters for example ‘Student’.
• Two connected words should start with a capital letter.
• Use whole words and must avoid acronyms and abbreviations.
Ogvjqfu
• Methods should be a verb.
• Should be in small letters.
• Two connected words should start with a capital letter.
Eqpuvcpv"xctkcdngu
• Should be capital letters with words separated by underscores (“_”).
Rcemcigu
• It should be small letters.
Kprwv"1"Qwvrwv"kp"lcxc
Before writing programs in java, we will discuss input and output in java.
Input statements allow the user to provide input for the program. While output
statements allow the user to display the output of the program. Java provides a
wide variety of input, which is discussed in detail in Chapter 5. Preliminary in
the next subsection we are going to discuss command line arguments.
Kprwv"vjtqwij"Eqoocpf"Nkpg"Ctiwogpvu
Like other programming languages, java allows the user to enter data
through the command prompt. Arguments passed through command prompt are
passed as arguments for function ‘main()’. These arguments are accepted as an
array of strings. The first value passed starts with string array. Following program
shows how command-line argument is passed –
In the above program main accepts arguments from the command prompt
which gets stored with String array ‘arg’. By accessing elements from array ‘arg’
we can read passed arguments. In the program, the argument value is assigned
Introduction to Java 17
While executing the program processor expects some argument from the
command prompt to build an array of Strings with the name ‘arg’. But here as
arguments are not passed, ‘arg’ remains empty array. But in execution, an
instruction tries to read values from the empty array as ‘arg[0]’. Hence processor
throws runtime error, an exception.
When the user passes arguments through command prompt, those all of type
‘String’. In the program, we need a different type of values, and hence these
command-line arguments need to be converted to the intended data type using
conversion methods from Wrapper classes. It is shown with the help of the
following the program –
18 Introduction to Java
While passing the input through command prompt values are passed in
sequence as int, float and double. In the same way, you can try for the ‘boolean’
data type.
Ikxkpi"Qwvrwv"wukpi"U{uvgo0qwv0rtkpv*+
In the above-given program, we have used instruction to display values of
variables –
[Link]("Your Name is "+name);
The statement above uses three keywords which we need to understand first.
Here ‘System’ is a class defined in ‘[Link]’ package. The class ‘System’
defines all necessary members which are required by the processor for basic
functionalities. The class ‘System’ defines three basic objects ‘in’, ‘out’ and
‘error’, which helps in handling basic functionalities. ‘out’ is an object on
PrintStream which outputs on the console. Using object ‘out’, which is a member
of the class ‘System’, we call the member method ‘print( )’. ‘print’ method helps
to display passed String on console. Here ‘print’ is a member of object ‘out’,
while ‘out’ is a member of class ‘System’, therefore to access them we use
Introduction to Java 19
Eqpvtqn"Uvtwevwtgu"kp"Lcxc
Using input, output and operators now it is possible for us to write simple
programs that deal with ‘input+process+output’. To alter the sequential execution
of instructions we need to know about control structures.
Dtcpejkpi"Uvcvgogpvu
When we have a choice of two different processes and have to select one
of these two, then we can go for branching statements. Like in ‘c’, java has also
‘if’ and ‘switch’ statements which allow us for branching.
1. if – Syntax for ‘if’ statement is given below –
if(<condition>)
{
<block to be executed when condition is true>
}
[else
{
<block to be executed when condition is false>
}]
NOTES
/*if in java for displaying maximum out of two numbers*/ class Max
{
public static void main(String arg[])
{
int num1=[Link](arg[0]); int num2= [Link]
(arg[1]); if(num1>num2)
{
[Link](num1+" is Maximum");
}
else
{
[Link](num2+" is Maximum");
}
}
}
Introduction to Java 21
Here two values passed are ‘45’, which is assigned to ‘num1’, and ‘82’
is assigned to ‘num2’. When ‘if’ is executed it goes for ‘num1>num2’.
Return of use of this relational operator is ‘false’, hence control goes
for execution of else block.
2. Nested ‘if’
In a situation where we need to check one more condition after
checking a condition then we go for nested ‘if’. In nested ‘if’ one ‘if’
is written within another ‘if’. Syntax for ‘nested if’ is shown below –
if(<condition>)
{
.
.
If(<condition>)
{
<block to be executed when condition is true>
}
else
{
<block to be executed when condition is false>
}
.
.
}
[else
22 Introduction to Java
As shown in syntax we can write ‘if’ within another ‘if’. When on the
condition is satisfied we want to check one more condition, then
‘nested if’ is used. 'if’ can be nested within ‘if’ as well as ‘else’ block.
The following program demonstrates the use of nested ‘if’.
/*if in java for displaying maximum out of three numbers*/
/*Nested if*/ class MaxThree
{
public static void main(String arg[])
{
int num1=[Link](arg[0]); int num2=
[Link](arg[1]); int num3=[Link](arg[2]);
if(num1> num2)
{
if(num1>num3)
{
[Link](num1+" is Maximum");
}
else
{
Introduction to Java 23
3. switch…case –
When a programmer needs to write nested if for multiple conditions,
where only one of the blocks is executed then nested if ladder can be
replaced by ‘switch’. ‘switch’ statement allows the user to check
multiple conditions and also reduces the complexity of the program.
Syntax for ‘switch’ is given below -
switch(<conditional variable>)
{
case <value1> :
<block of statements if value matches with value of variable> case <value2>
:
24 Introduction to Java
The program works like a calculator to carry out one of the four
operations on two integers. The program accepts three command-line
arguments from the user, first two are numbers on which arithmetic
operation will be carried out, while third is the option number for the
operation. As the program gives four different options for handling it
nested if it is required, which becomes complex. Here nested if can be
replaced by ‘switch..case’. Every case in switch mentions the option
number when the option is matched with the case, the case is executed.
The above command window shows output for the above program.
Here three executions for the same program are shown. For the first
two executions options are 3 and 1 entered, and according to option
26 Introduction to Java ‘case 3’ and ‘case 1’ is executed respectively. But in the third execution
Kvgtcvkxg"Uvcvgogpvu
Iterative statements are used when the execution of the same instruction
block is to be repeated. Iterative statements are categorized under two headings
– top tested and bottom tested. As the name suggests top tested statements test
output of condition before entering the block, on the other hand, bottom tested
statements test output of the condition at the end of the block. Both works
depending on the output of Boolean value but the place of accepting Boolean
value changes their nature of execution. As top tested checks value while
entering, if it is false the block is not executed, while bottom tested as tests at
the end though the value is false it is executed at least for one time. ‘for’ and
‘while’ are top tested statements while ‘do..while’ is bottom tested statement.
Now we will discuss each statement in detail.
1. while
It is top tested iterative statement syntax for which is given as –
while(<condition>)
{
<block to be executed iteratively>
}
At the entry of block, it checks for the condition, if the output of the
condition is false, it does not enter the block, and control is passed to
the nested statement after block. The following program shows the
working of the ‘while’ statement.
Introduction to Java 27
2. Do…while
It is bottom tested iterative statement syntax for which is given as –
do
{
<block to be executed iteratively>
} while(<condition>);
28 Introduction to Java
The program is the same as our previous program using ‘while’. Here
we have replaced ‘while’ with ‘do..while’ statement. There is no
change in the program, but a change in output can be observed. The
output of the first execution is the same as for ‘while. For the second
execution where value entered for ‘n’ is zero, the number ‘1’ has been
displayed. This is because of the use of ‘do..while’. Though here
condition ‘cnt<=n’ is not satisfied, the block is executed one time.
3. for –
Like while ‘for’ is also a top tested iterative statement. Syntax for the
statement ‘for’ is given as below –
for(<initialization>;<condition>;<increment/decrement>)
{
<block to be executed iteratively>
}
Introduction to Java 29
Cttc{u"kp"Lcxc
Array is a derived data type that allows the user to define ‘collection’. Hence
an array is defined as –
“ A collection of variables of similar data type which shares the same
name, and are stored in memory contiguously”
Continuous allocation of all elements in an array is one of the characteristics
of array elements. When users need a number of variables used in a program,
which are of the same data type then he can make use of arrays. Another
characteristic of array elements is ‘random access’. Though it is a collection each
element can be accessed randomly like a normal variable. The following
subsections explain the details of the arrays.
30 Introduction to Java
Kpkvkcnk|kpi"cpf"Ceeguukpi"Cttc{"Gngogpvu
In java declaration, allocation and initialization of array as shown below –
int arr[]={34,7,27,81};
the above instruction declares array with instruction ‘int arr[]’ and with the
instruction ‘={34,7,27,81}’ it instantiates and initializes the array. Here
Introduction to Java 31
32 Introduction to Java
NOTES
V{rgu"qh"Cttc{u
Till this time we have discussed only one-dimensional array, now in this
section we will discuss two dimensional arrays. Two-dimensional arrays are a
combination of rows and columns and hence while defining two-dimensional
array we need to mention the number of rows and columns. Syntax for defining
two-dimensional array is given as –
<data type><array name>[][]=new <data type>[<number of
rows>][<number of columns>];
For example, the following instruction shows how a two-dimensional array
can be declared –
int a[][]=new int[2][3] ;
While initializing two-dimensional array every row is written within curly
brackets which is shown with the following instruction –
int a[][]={{2,7,4},{9,1,8}} ;
For accessing array elements sequentially, like in one-dimensional array,
we need to use nested loops.
The outer loop represents rows while the inner loop represents columns.
Accessing array elements sequentially is shown with the following code –
/*Arrays in java */ class Array2D
{
public static void main(String arg[])
{
int a[][]={{2,7,4},{9,1,8}} ;
int j;
[Link]("Elements in Array 'a' are : "); for(int i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
[Link](" "+a[i][j]);
} Introduction to Java 33
Output for the above program is given in the command window below.
Uqog"Cttc{"Qrgtcvkqpu
In this subsection, we will see how we can perform some operations on
arrays. The following programs and their outputs demonstrate different
operations carried out on arrays of both types one dimensional and two
dimensional.
1. Adding two one dimensional arrays –
/*Arrays in java */ class AddArray1D
{
public static void main(String arg[])
{
int a[]={2,7,4};
int b[]={9,1,8};
int c[]=new int[3]; int i;
[Link]("Elements in Array 'a' are : "); for( i=0;i<3;i++)
{
[Link](" "+a[i]);
}
[Link]("Elements in Array 'b' are : "); for(i=0;i<3;i++)
{
[Link](" "+b[i]);
}
[Link]("Elements in Array 'c' after addition are : ");
34 Introduction to Java
NOTES
36 Introduction to Java
Introduction to Java 37
NOTES
NOTES
*****
Introduction to Java 39
UNIT - 2
CLASS AND OBJECT
NOTES
CONCEPTS
Ejcrvgt"Qdlgevkxgu"
To understand –
o Characteristics of OOP Languages
o Defining and Using Classes
o Hiding data in classes using different Modifiers
o Defining and Using Package
o Exception Handling in Java
Qdlgev/Qtkgpvgf"Eqpegrvu"kp"Lcxc
Object-Oriented Programming is the outcome of the need for providing
security to data to be processed by different programming constructs
(functionalities). The basic requirement of any software is to process data. While
performing different operations on data, one needs to keep the data safe from
processes that change this valuable data. This need had given rise to OOP
concepts which are discussed below.
Fcvc"Jkfkpi"cpf"Fcvc"Cduvtcevkqp
With the POP (Procedure Oriented Programming) paradigm the problem
faced is ‘data security’. In POP there is no provision to provide any protection to
data from processes. These processes may access and change data.
When a user needs data-centric software, where data is valuable and needs
to protect from intended access by processes. This has given rise to the need to
hide data from processes. To provide protection to data from processes there is a
need to hide data. This was the reason why they need for the new paradigm was
felt. Data hiding was the basic concept of OOP.
To hide data from the external environment one needs to abstract data with
the help of the concept of ‘data abstraction’. With the help of data is grouped
together to explain an object. For example, to store data of an employee in a
company, we can group data, which explains an employee like employee id,
employee name, joining date, department, and name this group as ‘Employee’.
Here group name ‘Employee’ is abstraction which helps to hide unnecessary
Class and Object information from others.
40 Concepts
Encuu
Class is a software construct that helps to implement above-discussed
concepts of Data hiding, data abstraction, and data encapsulation. Class allows
the programmer to define their own abstraction. It is a template that helps to bind
data and operations on data together. Class is a blueprint of objects and explains
how objects can store and process data. The class definition also allows adding
visibilities to its members at different levels i.e. visibility at class level, or at the
object level, for derived class and so on.
Qdlgev
Object is a runtime entity. On a class, user can define an object which helps
to store and process data. Class does not occupy any memory space, but the object
occupies memory. Objects hold their own personal data which cannot be shared
with other objects in the system if the class does not permit to share it. For eg.
On class Employee if two objects are defined namely ‘objE1’ and ‘objE2’ then
these two objects are used to store data for two different employees which cannot
be shared or processed by each other if class ‘Employee’ does not define such
method.
Class and Object
Concepts 41
Rqn{oqtrjkuo
It is a Greek word which means ‘one thing with many forms’. In OOP from
the programmer's point of view to introduce easiness in programming and to add
the feature of ‘dynamic binding’ or ‘runtime binding’, the concept of
‘Polymorphism’ was introduced. Following two programming constructs helps
to implement polymorphism in programs –
• Method Overloading – The concept allows the developer to define
different function blocks with the same name and varying either number
or type of arguments.
• Method Overriding – inheritance allows the developer to reuse
properties from predefined class, while Overriding allows the developer
to modify functionalities from predefined class without changing their
names.
These two concepts support static binding. For dynamic binding virtual
functions are used which is implemented in java with the help of –
• Dynamic Method Dispatch – As the name suggests it decides runtime
the method for which object is to be executed where references are
defined for classes that are arranged hierarchically.
Oguucig"Rcuukpi"qt"Cuuqekcvkqp
The basics behind the development of the OOP paradigm are to provide
security to data. Hence ‘Object’, the basic entity of the OOP program which is
responsible to carry out major programming tasks, tries to hide data from the
external environment i.e. other components (objects) of system. If every
individual component of the system tries to hide system data from each other,
then the system cannot work properly. Therefore there is a need to have
communication among different components. This communication can be
developed with the help of ‘message passing’ or ‘association’. If any component
from the system, for completing its task needs some data from others, it can send
a message to the component. In return, the associated component will send the
required data. This association is defined with the help of methods added in class.
But the association between two classes needs to be defined at the design level.
Class and Object This message passing takes place between two objects. For [Link] to generate bill
42 Concepts
Fghkpkpi"c"encuu
In this section, we are going to see how to define a class in java. As
discussed earlier, the class helps the user to encapsulate data and methods
together to implement data abstraction. Class is assigned with name, which is
treated as User Defined Data type in java. Syntax for defining class is given as
below-
<access modifier>class <class name>
{
/*Definition of members*/
}
In the above syntax, we can observe that the class definition starts with an
access modifier, which decides the visibility of class. The access modifier is
optional and if not mentioned java compiler treats it as a default modifier and is
accessible within the same package. Access modifiers are discussed in upcoming
chapters.
After access modifier, the keyword ‘class’ is used, which explains compiler
that a new user-defined data type is being defined. The keyword is followed by
‘class name’.
The class name defines a new user-defined data type, which decides how
and how much bytes should be allocated. The name assigned to class always is
a noun and helps to get an idea about what data is being presented.
The class name is followed by delimiters that define the scope of the class.
The attributes (variables) and methods (functions) defined within these delimiters
are covered under the scope of the class and hence are known as members of the
class.
For example, if a class to be defined to store data of an employee working
in a company, is explained with the help of the following code.
public class Employee
{
/*Definition of members in class Employee*/
}
The above code snippet explains how to start the definition of the class. The
code is explained below- Class and Object
Concepts 43
Cffkpi"Cvvtkdwvgu"vq"Encuu
The word ‘attribute’ means the properties or characteristics of an object.
These properties help to describe and understand an object. Properties of an
object are stored with the help of variables which are defined as members within
the class. Syntax for adding attributes in a class is as below –
<access modifier> class <class name>
{
<access modifier><data type><attribute name>;
/*Definition of methods*/
}
Now we will see the explanation for highlighted instruction. The instruction
gives syntax for defining attributes in a class. The syntax is explained below.
• Access modifier – To add visibility to the attribute access modifier is
used. It is optional, if not mentioned ‘default’ access modifier is assigned.
• datatype – Every attribute needs to be defined with data type, which
explains the type of value stored by an attribute.
• attribute name – Name of the attribute which helps in referring it. The
attribute names should follow the same rules as for the variable name.
There is no restriction on the number of attributes can be added to the class.
A class developer can add any number of attributes as per requirement. Following
code, snippet explains how a class can be defined –
public class Employee
{
protectedintempId, private intbasicSal;
private String empName, address;
Cffkpi"Ogvjqfu"vq"Encuu
While discussing data hiding and encapsulation, we have discussed, as an
OOP language, java allows the user to encapsulate (group) data and methods
processing on data together. Methods are user- defined functions that define a
process block to process data. These methods can be executed by an object to
process its own data. As these methods are predefined, other than these methods
any process cannot be carried out on data by the external environment. Syntax
for adding methods to the class is given below–
<access modifier> class <class name>
{
<access modifier><data type><attribute name>;
<access modifier><return data type><method name>(<list of arguments>)
{
<process block>
}
}
In the above code, two methods are defined one is setData and getName.
These two methods are public which are accessible out of class using the object.
Etgcvkpi"Qdlgevu"qp"c"encuu
A class helps the developer to define his own data type which encapsulates
data and methods operating on it together. It is a blueprint of data, but cannot be
used to store and data. Data can be stored and processed with the help of objects
declared on a class. Object is a runtime entity and occupies memory to store data.
Through object methods and attributes, defined with public access specifier can
be accessed. Before defining objects for class make sure that source code for the
class is compiled to generate its bytecode.
Syntax for defining an object on class is given in following code –
<class name> <object name>;
It can be observed that syntax for defining an object is the same as defining
a variable for built-in data types. Java treats the class as a normal data type and
allows to use class name as a data type while defining an object. Following code
explains how an object can be defined on predefined class -
Class and Object Employee objEmp;
46 Concepts
Uvgru"hqt"Etgcvkpi"Qdlgev
Following steps should be followed to avoid errors –
(1) Define a class with proper attributes and methods.
(2) Compile class to have its ‘.class’ file with you.
(3) Compile program which declares object on class.
As discussed earlier, while declaring an object, bytecode (‘.class’ file) for
class definition should be available. The bytecode for each class definition is
generated after compiling ‘.java’ file. There are different methods of how a class
and its object can be declared –
k+ Fghkpkpi"encuu"kp"vjg"ucog"uqwteg"hkng"⁄
Here we are going to discuss how we can define two classes, one is user-
defined while the other is to implement it, in one source file with extension
‘.java’. After compiling this file two bytecode files are generated. While
executing these class files we need to execute the bytecode file for the class which
contains function ‘main()’.
It is explained with the help of following code –
/*Source code file name : [Link]*/
/*Definition for class Employee which is user-defined class*/ class
Employee
Class and Object
{
Concepts 47
NOTES
kk+ Fghkpkpi"encuu"kp"cpqvjgt"uqwteg"eqfg"hkng"kp"ucog"fktgevqt{/
Under this option we create two different source code files, one for defining
user defined class while another to implement it. While storing these two files
take care that both files will be in same folder. Following two codes explains the
program.
/*Source code file name : [Link]*/
/*Definition for class Employee which is user defined class*/ public class
Employee
{
protected int empId, private int basicSal;
private String empName, address;
public void setData(int eid,int bsal,String ename, String add)
{
empId=eid; basicSal=bsal; empName=ename; address=add;
}
public String getName()
{
Return(empName);
}
}
Firstly create first source file and save it with name ‘[Link]’. Then
create second source code file and save it with name ‘[Link]’.
While compiling files from command promptnow two different files should
be compiled. First compile file ‘[Link]’, which creates ‘[Link]’.
In the next step compile file ‘[Link]’. This creates class file for
‘[Link]’. to execute the code execute class file ‘EmpImp’, as it contains
function main().
/*Definition for class EmpImp which implements class Employee*/ public
class EmpImp1
{
public static void main(String arg[])
Class and Object
{ Concepts 49
kkk+ Fghkpkpi"encuu"kp"cpqvjgt"uqwteg"eqfg"hkng"kp"qvjgt"fktgevqt{"⁄
Here with this option a package is created having definition of class and the
package is added to the source code using ‘import’ command. The process of
creating package and using classes from package is explained in section 2.7.
Ceeguukpi"Ogodgtu"htqo"encuu"wukpi"Qdlgev"
In the previous section we have seen that object is used to store data and
process data. Object is an entity which can access members of class depending
on their visibility. In this section we are going to discuss how members in class
can be accessed.
Membership operator (‘.’) is used to access members using object. Syntax
for accessing member is given below –
<object name>.<member name>;
The above syntax helps to access members for class. In the last code snippet
in ‘main()’ function we can observe, how members from class can be accessed
using object on class.
[Link](10,20000,"XYZ","Pune");
In the above code ‘objEmp’ is the object on class Employee, while
‘setData()’ is member method with access modifier ‘public’. When this member
method is to be called, it is called through object on class ‘Employee’ using
membership operator.
Eqpuvtwevqtu
In 2.3 section we have discussed about declaring object on class. While
Class and Object allocating memory space for an object, as mentioned earlier, we use keyword
50 Concepts
Ejctcevgtkuvkeu"qh"Eqpuvtwevqt"
• It is a method without any return data type. Its return type is class type.
Constructor from any class constructs object and return its reference, and
so there is no need to define any data type for constructor.
• Its name is same as class name. Other than constructor any other method
cannot have same name as class name.
• It is executed by processor while creating an object without any explicit
call.
• Its access modifier depends on developer. Developer can decide who can
use the constructor to construct an object. This point is again discussed
in detail while discussing inheritance.
Pggf"qh"Eqpuvtwevqt"
Whenever, an object on a class is defined, needs to be allocated and
initialized. Initialization of an object is the task carried out by the constructor.
Initialization can be done either by processor or user can write his own
constructor.
For example if an object named ‘objEmp’ is declared on class ‘Employee’,
before calling any method using object to process data from object, it needs to
be initialized. It is done explicitly by constructor.
Fghkpkpi"c"Eqpuvtwevqt"kp"c"encuu"
If any class does not define any constructor then also objects on class are
allocated and initialized, but the initial values assigned are same for all objects.
If developer wants to initialize objects with their own personalized values while
being declared, he can add constructor to the class definition. A user defined
constructor in a class helps to initialize an object at the same time when it get
allocated with memory.
Defining constructor is nothing but adding a method to class definition with
same name as class name and without any return data type. While discussing
types of constructors (section 2.4.4) various syntaxes along with sample code for
defining a constructor are discussed in detail. Class and Object
Concepts 51
*3+ U{uvgo"Fghkpgf"Eqpuvtwevqt
We have discussed that any object cannot be declared without constructor,
and therefore every class, while compiling, needs constructor definition. If
developer has not defined constructor in class, compiler adds its own constructor
to class definition. Here the constructor added by compiler is ‘default constructor’
or ‘no argument constructor’. This constructor initializes the object attribute to
either zero or to null depending on its data type.
Following code explains working of a system defined constructor.
/*Source code file name : [Link]*/
/*Definition for class Employee which is user defined class*/ class
Employee
{
protected int empId; private int basicSal;
private String empName, address;
public void setData(int eid,int bsal,String ename, String add)
{
empId=eid; basicSal=bsal; empName=ename; address=add;
}
public void displayEmpData()
{
[Link]("\nID : "+empId+"\nName : " + empName + "\nAddress
: " + address);
}
}
/*Definition for class EmpImp which implements class Employee*/ class
EmpImp
{
public static void main(String arg[])
Class and Object
52 Concepts
In the above output window data for same object has been displayed for
two times. Firstly when method ‘displayEmpData()’ is executed it shows zero
value for ‘empId’ which is numerical variable, while ‘null’ for ‘empName’ and
‘address’ which are String variables. This initialization is done using system
defined default constructor.
Compiler can add only default constructor to the class definition.
*4+ Wugt"Fghkpgf"Fghcwnv"Eqpuvtwevqt"⁄
If user wants to assign his own initial values to attributes in an object then
he can define his own constructor without any arguments, which is known as
user defined default constructor. User can add his own default constructor by
modifying class definition with following syntax–
<access modifier> class <class name>
{
<access modifier><data type><attribute name>;
<access modifier><class name> ()
{
<process block>
}
Class and Object
<access modifier><return data type><method name>(<list of arguments>) Concepts 53
In the above block of syntax highlighted text shows syntax for adding user
defined default constructor to the class.
The constructor definition starts with access modifier, generally for
constructor it is ‘public’. In certain situations it may be defined as ‘private’ or
‘protected’.
Access modifier is followed by class name. Constructor, as discussed earlier,
is a special method having same name as class name. It does not have any return
data type so though it a method here return data type is not mentioned.
After class name empty brackets are given, which denotes constructor does
not accept values while getting call. It is no argument constructor and therefore
it is known as default constructor.
With the help of following program we can understand use of default
constructor.
/*Source code file name : [Link]*/
/*Definition for class Employee which is user defined class*/ class
Employee
{
protected int empId; private int basicSal;
private String empName, address;
public Employee()
{
empId=0; empName="XXX";address="Pune"; basicSal=1000;
}
public void setData(int eid,int bsal,String ename, String add)
{
empId=eid; basicSal=bsal; empName=ename; address=add;
}
public void displayEmpData()
{
kk+ Rctcogvgtk|gf"Eqpuvtwevqt
The constructor which accepts arguments is called parameterized
constructor. As against to default constructor, parameterized constructor
initializes the object with passed values and hence every object defined on a class
can have their own personalized values. The syntax for defining a parameterized
constructor is given below –
<access modifier> class <class name>
{
<access modifier><data type><attribute name>;
<access modifier><class name> (<list of parameters along with data type>) Class and Object
Concepts 55
kkk+ Eqr{"Eqpuvtwevqt
When data from one object is to be copied to other object, the copy
constructor is defined. Copy constructor is a parameterized constructor which
accepts reference to object. Data from this passed object is to be copied to newly
created object. Following program explains copy constructor.
/*Source code file name : [Link]*/
/*Definition for class Employee which is user defined class*/ class Employee Class and Object
Concepts 57
Rcuukpi"xcnwgu"vq"hwpevkqpu
Every function block stores its values as local values and accessible within
the block only. When a call to another function block is given and if a block need
values from calling function block these values need to be passed while giving
call. These passed values are known as arguments. Following program shows
why one needs to pass values to functions –
/*Passing values to functions*/ class PassArguments
{
static int sqWithArg(int c)
{
return(c*c); Class and Object
Concepts 59
Rcuu"d{"Xcnwg NOTES
In pass by value first type of reference to value is used. While giving call
to function name of the variable is passed to called function. Here value of the
variable, whose name is mentioned, is passed to block and is copied to passed
function block with new variable name, and so the concept is known as ‘pass by
value’.
The program given above is the function with ‘call by value’. Here while
giving call to function ‘sqWithArg()’ variable ‘a’ is passed to function. When
control is transferred to function ‘sqWithArg()’ from ‘main( )’ it is transferred
with value of ‘a’ and it is assigned to variable ‘c’. The value of ‘c’, which is
actually value of ‘a’, is processed and resultant value is returned to calling
function.
Drawback of ‘pass by value’ is, if called function does not return value to
calling function, calling function cannot get result.
Rcuu"d{"Tghgtgpeg
In pass by reference, instead of passing value its memory address is passed
to calling function. Now calling function can access value from the address
directly and hence the process on value is carried out at the memory location
directly. So in this concept though calling function does not return any value, the
original value is changed.
But java does not support ‘pass by reference’. While discussing
characteristics of java, it is discussed that java does allow user to access memory
directly. It is to make it platform independent, JVM decides strategies for
managing memory. But this feature does not allow java developer to write
functions for pass by reference.
Hwpevkqp"Qxgtnqcfkpi
Concept of function over loading comes under Polymorphism. Using a
single function name with either different number of arguments or different type
of arguments is known as ‘Function Overloading’. The concept is discussed in
detail in chapter 3 under Inheritance and Polymorphism.
Oqfkhkgtu
While defining functions and variables along with data type different
modifiers can be added to add some more features to their accessibility while
execution of program. All modifiers are classified under four categories which
are discussed in following sub sections.
k+ Rtkxcvg"
It is a keyword used with members which are accessible within class
definition only. Delimiters given after class name define scope of class. Private
members scope is within class, i.e. these members can be accessed within these
two delimiters. Following syntax shows scope of private members –
class <class name>
{
private <data type><member name>;
.
.
.
}
Highlighted area shows scope for the private members. Member definition
is preceded by keyword private. Private member is accessed like a normal
variable. Though it is a member of a class, to access private member there is no
need of object. Following program shows how a private member can be defined
and used.
class PrivateDemo
{
private int n;
}
Here ‘n’ is an integer variable whose access modifier is ‘private’ and hence
it is accessible within class definition. If we execute following code it will
generate compilation error –
Class and Object
class PrivateDemo
62 Concepts
Vjg"gttqt"ikxgp"d{"eqorkngt"ku"ikxgp"cu"⁄
kk+ Rwdnke
This is another keyword which allows user to add other type of accessibility
to members. These are members who are accessible in class as well as outside
the class definition. When public members are accessed within class it can be
accessed directly like normal variables, but outside the class definition these are
accessed through object. Following syntax shows how to declare and access data
members.
class <class name>
{
public <data type><member name>;
}
Here as the scope of public member is outside the class also, so there is no
highlighted text. Class and Object
Concepts 63
Fghcwnv
The modifier assigned to members by default is called as ‘default’. When,
while defining member in a class no modifier is specified then its access is
default. The default access allow the member to be accessed within the folder
where the class is defined.
Uvcvke
‘static’ is a keyword used with declaration of variables or functions. It is a
modifier which changes scope and lifespan of a variable as well as functions.
Firstly we will discuss effect of static with variables and then with functions.
K0 Uvcvke"Xctkcdngu"⁄
Static variable in a class is treated differently than a normal member
variable. Characteristics of a static variable are given as –
• It is initialized automatically by data type’s initial value.
• It is allocated commonly and accessed commonly in different function
calls.
• It’s last value is retained within different function calls.
• Only static methods can access static variables.
Use of static variables in a function block is explained with the help of
following program –
/*Static Variable in Function*/ class StaticTrial
{
static int sn;
static void staticTest()
{
int n=0; n++;
sn++;
[Link]("\nNormal Variable n="+n+"\nStatic Variable sn="+sn); Class and Object
Concepts 65
Htqo"vjg"qwvrwv"yg"ecp"qdugtxg"vjcv"⁄
- Value for ‘n’ is common for all function calls. As it is a normal variable
for every call it gets allocated and initialized.
- Value for ‘sn’, on the contrary, goes on changing for each call. This is
because when function is called for the first time ‘sn’ is allocated and
initialized to zero, and same is used by next function calls. As it is
allocated in shared memory, same value is shared and retained in different
calls. Therefore for first call value is ‘0’ which is incremented to ‘1’, in
next call ‘1’ is incremented to ‘2’ and in third it becomes ‘3’.
KK0 Uvcvke"Ogodgtu"
The methods, defined as members in a class, uses static modifier does not
need object on a class to access it. It can be accessed without object using only
class name. Syntax for accessing static members is given as –
<class name>.<member name>;
So here while accessing static members object on class is not required.
Though the object on class is not defined, yet static members can be accessed.
Following program helps to understand concept of static members in a class
–
/*Static Method in a class*/ class StaticMethod
Class and Object
{
66 Concepts
Hkpcn
It is a keyword used with two contexts –
- With variable values
- With members of a class in inheritance
- With class
In this sub section we will see how it can be used with variable values.
When we need to define constants, we can use ‘final’ keyword. For example
Class and Object
68 Concepts final float PI=3.14f;
If we remove the keyword ‘final’ from declaration of ‘PI’, the program will
execute successfully. Following program shows how we can use ‘final’ to declare
constant variables.
/*Defining constants with keyword 'final'*/ class FinalImp
{
public static void main(String args[])
{
int r=5;
final float PI=3.14f; float area=PI*r*r;
[Link]("Area of Circle = "+area);
}
}
Class and Object
Concepts 69
NOTES
Cttc{"qh"Qdlgevu
Just like ‘array of variables’ defined for primitive data types, ‘array of
objects’ can be defined on user-defined datatype. Syntax for defining an array of
objects is given below –
<class name>[ ] <array name> = new <class name>[<size of array>];
An array of objects helps the user to store data for multiple objects, which
are allocated contiguously in memory. The following program explains how to
declare and access array elements.
/*Array of objects*/ import [Link].*; class Employee
{
private String name; private int empId; public void getData()
{
Scanner s=new Scanner([Link]); [Link]("Enter Employee
Name : "); name=[Link]();
[Link]("Enter Employee Id : "); empId=[Link]();
}
public void display()
{
[Link]("Employee Name : "+name+"\nEmployee Id : "+empId);
}
}
class ArrayObject
{
public static void main(String arg[])
{
Employee[] arrEmp=new Employee[4];
Class and Object //Initialization of Array Elements for(int i=0;i<4;i++)
70 Concepts
Rcemcigu
The Package is defined as –
‘a collection of classes and interfaces which can be used in other programs
by importing it’.
Classes which need to be grouped together, as they share common
functionalities, then the concept of package is used.
For example suppose in a software system developed for ‘Hospital’ defines
different classes for processing data of patients and their health data, as well as
bills paid by them. Patients visiting hospital are categorized as OPD patients and
IPD patients. According to type of patient, format of their health data and bill
data goes on changing. For processing this data various classes are defined, from Class and Object
Concepts 71
Uvgru"kp"Fghkpkpi"c"Rcemcig
By applying following steps a package can be created –
1. Create a folder with package name. The folder resides in same
directory where package will be used.
2. Every class or interface defined as a part of package starts with
package definition. Syntax for package definition is given as –
package <package name>;
The keyword ‘package’ explains that the class file is a part of package.
It should be the very first line in file, and is followed by ‘import’ if
necessary.
3. The class or interface, which is defined as part of a package, needs to
be assigned with proper access modifier. If the class is to be used
outside the package then its access modifier should be defined as
‘public’, if not then no need to define any access modifier as it is
assigned with ‘default’ access modifier.
4. Like normal program file save file with extension ‘.java’. If access
modifier used for class is ‘public’ then save the file with same name
as class name. For each class and interface in a package create a
separate file.
5. Compile each file and store its ‘.class’ file in the same folder.
These steps are to be followed while creating our own package. In this
section we have discussed only about creating single package. So package will
have only collection of classes and interfaces, and no other packages. The next
sub section discusses about defining packages in hierarchy.
Etgcvkpi"jkgtctej{"qh"rcemcig
While forming hierarchy of packages, we will have nested packages. In
simple language we will have one package inside the other package. The
following diagram explains diagrammatically how hierarchy can be formed.
NOTES
classes for OPD and IPD. Now we have two packages OPD and IPD, and
collectively these two packages are kept as a group in one package i.e. ‘Hospital
Package’. So it forms hierarchy of packages.
The hierarchy of packages can be created by creating directory hierarchy.
For eg. In ‘HospitalPackage’ we have two sub packages ‘OPD’ and ‘IPD’ then
in current working directory we will have subdirectory ‘MyPackage’. In
‘MyPackage’ we will have subdirectories ‘MyPack1’ and ‘MyPack2’.
While defining classes in ‘OPD’ the package will be defined as –
package [Link];
Korqtvkpi"rcemcig
In the above sections we have seen how packages can be created. Now the
section discusses about using predefined packages. When a package is to be used
make assure that the package folder is in the same directory where you are using
it. Before using classes from the package in a program for declaration of objects,
the package for the class should be made available. Here to make class definition
available from package ‘import’ statement from java is used. Syntax for using
‘import’ is given below –
import <super package>.<sub package>…<class>;
Whenever a package is to be used so that the member of package will be
available for use (classes, interface, & methods defined in package) then using
statement import user can import the package while importing the package the
user can make use of ‘.’ operator to specify the member name from the package.
For example, we need definition of class ‘Card’ to define its object in a
program then we can import package ‘OPD’ as –
import [Link];
Here ‘HospitalPackage’ is a package at higher level while OPD is its
member package, and in OPD package we have class ‘Card’. Using dot operator
(‘.’) we can access one package nested in other.
ß Wug"qh"Uvct"*,+"yknfectf
It is a wildcard which denotes ‘all’ members from package when instead of
Class and Object
specifying a particular class or interface user wants to use all members from the Concepts 73
Gzegrvkqp"Jcpfnkpi
The section discusses about the handling of runtime errors. Programmers
while compiling and executing programs face different kind of errors. Depending
on type of error, error handling techniques are applied to remove it and execute
the program smoothly. Java provides a powerful error handling technique which
helps in handling runtime errors known as exceptions and hence known as
‘Exception Handling’. Before starting with different types of exception handling
we need to know about types of errors discussed in next section.
V{rgu"Gttqtu
Different errors which may occur while executing program are roughly
categorized under three headings. Each type of error along with its example is
discussed below –
k+ U{pvcz"Gttqtu
The errors which can be detected by compiler are termed as Syntax errors.
These errors are also known as compilation errors. Mistakes in keyword
spellings, errors in punctuation marks, and use of undeclared variables,
unmatched blocks are syntax errors. If the program has any syntax errors,
compiler cannot complete the compilation process and hence the program cannot
be executed. The program having syntax/compiler errors is possible to execute
only after removing these errors.
For Example following code shows a syntax error –
Class Trial
{
public static void main(String arg[])
{
[Link]("Welcome to Java");
}
}
If the above given program is compiled, then java compiler cannot complete
the compilation and lists syntax error as shown in figure below –
Class and Object
74 Concepts
NOTES
This error is due to the using keyword as ‘Class’ instead of ‘class’. Java is
case sensitive and hence java compiler differentiates in these two words, hence
cannot complete compilation. Here the class file is also not generated for the
program.
kk+ Nqikecn"Gttqtu
Though the program is compiled and executed successfully, when the
desired output is not given then it is known as logical errors. Logical errors are
caused due to wrong sequence of instructions, wrong use of operators or wrong
data type. These errors are hard to found and to remove and programmer needs
to take pains for removing these errors.
Following program shows how logical errors can occur –
/*Program to display largest out of two*/ class Logical
{
public static void main(String arg[])
{
int a=10,b=15; if(a<b)
[Link]("a is largest.");
else
[Link]("b is largest.");
}
}
Above program outputs the largest variable name as an output. The program
is compiled and executed successfully. But the output is unexpected. Here we
should get output as ‘b is largest’ but it displays ‘a is largest’. This is because of
wrong use of operator. While comparing two variable values, a and b,
programmer has used ‘less than’ (<), but here it should be ‘greater than’(>). This
is the reason why the program is not giving right output. It is the logical error.
All such different exceptions which may abort the program execution are
defined in package ‘[Link]’. In next sub sections we will discuss how these
exceptions can be handled in java.
flvt{‚"Dnqem
The instructions which might get runtime error are written within ‘try’
block. Whenever try block is executed every instruction in try block is executed
carefully. As and when exception (runtime error) occurs, it is thrown to be caught
by corresponding ‘catch block’ which handles that exception.
flecvej‚"Dnqem
‘catch’ block is always written after end of try block. The catch block Class and Object
accepts ‘Exception’ type as an argument. When an exception is thrown by try Concepts 77
NOTES
Ownvkrng"flecvej‚"dnqemu"hqt"ukping"flvt{‚
In the program discussed in previous sub section other instructions also can
throw other type of exceptions. Here program is accepting input as command
line arguments. If user fails to provide it, the program terminates with an
exception namely ‘ArrayIndexOutOfBounds’. Command line arguments are
accepted as an array of strings, which are passed as arguments to function
‘main()’. If user does not pass any values, but in program instruction tries to read
elements from String array as –
a=[Link](arg[0]);
then the instruction throws an exception, which need to be caught and
handled. Following command window shows how exception is thrown when no
command line arguments are passed to ‘main()’ –
Here as program is small a single try block can handle all exceptions with
the help of multiple catch blocks. We can modify the previous program to handle
these multiple exceptions. Following program shows modification of previous
program to handle these multiple exceptions.
/*Program to display division after dividing a by b*/
/*Program accepts command line arguments*/ import [Link].*;
class DivideZero
{
public static void main(String arg[])
{
int a,b,c; a=0;b=0;c=0; Class and Object
Concepts 79
flhkpcnn{‚"dnqem
In the previous execution of multiple blocks we have seen that there is no
proper sequence for execution of catch blocks and it may alter all execution
sequence. When exceptions are thrown, execution in a method takes a rather
abrupt, nonlinear path that alters the normal flow through the method. Depending
upon how the method is coded, it is even possible for an exception to cause the
method to return prematurely. This could be a problem in some methods. For
example, if a method opens a file upon entry and closes it upon exit, then you
will not want the code that closes the file to be bypassed by the exception-
handling mechanism. The finally keyword is designed to address this
contingency. finallycreates a block of code that will be executed after a try/catch Class and Object
block has completed and before the code following the try/catch block. The Concepts 81
Pguvgf"vt{"Uvcvgogpvu
The try statement can be nested. That is, a try statement can be inside the
block of another try. Each time a try statement is entered, the context of that
exception is pushed on the stack. If an inner try statement does not have a catch
handler for a particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match. This continues until one of
the catch statements succeeds, or until all of the nested try statements are
exhausted. If no catch statement matches, then the Java run-time system will
handle the exception.
Nesting of ‘try’ block can be shown with the help of following program –
/*Program to display division after dividing a by b*/
/*Program accepts command line arguments*/ import [Link].*;
class DivideZero
{
public static void main(String arg[])
{
int a,b,c; a=0;b=0;c=0;
try
{
Class and Object a=[Link](arg[0]); b=[Link](arg[1]); c=a/b;
84 Concepts
*****
UNIT - 3
INHERITANCE
NOTES
AND POLYMORPHISM
Ejcrvgt"Qdlgevkxgu"
To understand –
o Concept and Importance of Inheritance
o Types of Inheritance
o Polymorphism and Implementation of Overloading and Overriding
o Dynamic Binding with the help of Dynamic Method Dispatch
o Multiple inheritance with Interface
Eqpegrv"cpf"Korqtvcpeg"qh"Kpjgtkvcpeg
Inheritance is the mechanism which allows a class to use properties
(attributes) and behaviour (methods) from its parent class. The feature helps to
define a new system based on the existing system. With the help of inheritance
properties predefined with previously defined class can be used by newly defined
class. Here previously defined class is known as ‘parent class’ or ‘super class’
while newly defined class is known as ‘child class’ or ‘sub class’. The sub class
derives members from super class hence it is also known as ‘derived class’.
Diagrammatically inheritance can be represented as –
V{rgu"qh"Kpjgtkvcpeg
The concept of inheritance can be implemented in various types. These
categories or types are based on the number of super classes used for
implementing inheritance. While implementing inheritance through programs
depending on number of super classes use to drive or define sub-classes different
categories can be defined as –
i) Simple or Single inheritance
ii) Multiple inheritance
iii) Multilevel inheritance
iv) Hierarchical inheritance
v) Hybrid inheritance
Every category or type of inheritance along with the program is explained
in next sub sections. Before discussing all types in detail there is need to
understand how to implement inheritance.
Inheritance
88 and Polymorphism
Uwd"Encuu"Fghkpkvkqp"⁄
Sub class definition starts like a normal class, but is extended with super
class name using keyword ‘extends’. The concept of inheritance helps to relate
two classes which help in data sharing. The relation of inheritance is defined with
keyword ‘extends’. The keyword ‘extends’ define the sub class as extension of
its super class. Syntax for defining sub class by using keyword ‘extends’ is given
as –
<access modifier> class <sub class name> extends <super class name>
{
<definition of sub class>
}
In the above syntax highlighted line shows how sub class definition should
start. As we can see class definition starts like a normal class. After class name
the keyword ‘extends’ explains the class is a sub class of the class whose name
is mentioned after keyword.
For example if class ‘Parent’ is super class for class ‘Child’,
diagrammatically which is represented as –
Inheritance
and Polymorphism 89
Ukorng"qt"Ukping"kpjgtkvcpeg"
When sub class is derived from a single super-class then the type of
inheritance is known as simple or single inheritance. Diagrammatically it is
represented as –
Inheritance {
90 and Polymorphism
“Only for Private Circulation”
a=i;b=j; Java Programming
}
public void displayA()
NOTES
{
[Link]("\nObject OF class A: \nClass A: a= "+a+"\nb= "+b);
}
}
class B extends A
{
private int c;
public void setDataB(int i,int j, int k)
{
[Link](i,j);
c=k;
}
public void displayB()
{
[Link]("\nObject
OF class A: a="+a+"\nb= "+b+"\nClass B: c= "+c);
}
}
class SimpleInheritance
{
public static void main(String arg[])
{
A obA=new A(); B obB=new B();
[Link](4,5);
[Link]();
[Link](40,50,60);
[Link]();
}
}
Inheritance
and Polymorphism 91
Ownvkngxgn"kpjgtkvcpeg"
In multilevel inheritance a sub class is derived from a single super class
which is again sub class of another super class. Diagrammatically it is represented
as –
For ‘obB’ memory is allocated for its own members that is ‘c’, ‘setDataB()’
and ‘displayB()’ as well as for its derived members from super class ‘A’, namely
‘a’, ‘b’, ‘setDataA()’ and ‘displayA()’.
While for ‘obC’, which is object on class ‘C’, memory is allocated for its
own members namely ‘n’, ‘setDataC()’, ‘displayC()’. From class ‘B’ and hence
class ‘A’ it derives members ‘c’, ‘setDataB()’ and ‘displayB()’ as well as ‘a’, ‘b’,
‘setDataA()’ and ‘displayA()’ respectively. So though class ‘C’ defines only one
variable, its object can store data for four variable, one for its own and other three
from its super classes.
Output for the above program is shown below –
Jkgtctejkecn"kpjgtkvcpeg"
When from a super class more than one sub classes are derived then the
type is known as hierarchical inheritance. Diagrammatically it is represented as
–
Inheritance {
96 and Polymorphism
“Only for Private Circulation”
private String n; Java Programming
public void setDataC(int i,int j, String k)
{
NOTES
[Link](i,j); n=k;
}
public void displayC()
{
[Link]("\nObject for class C:\nFrom class A: a= "+a+"\nb=
"+b+"\nFrom class C: n= "+n);
}
}
class HierarchicalInheritance
{
public static void main(String arg[])
{
A obA=new A(); B obB=new B(); C obC=new C();
[Link](4,5); [Link]();
[Link](40,50,60); [Link]();
[Link](400,500,"ABC");
[Link]();
}
}
Above program defines four classes as in previous one. Classes are named
as class ‘A’, class ‘B’, class ‘C’ and class ‘HierarchicalInheritance’, from which
first three are user defined classes, and fourth is class for implementation. Here
class ‘B’ and class ‘C’ are related with Class ‘A’, but these two classes does not
have any relation with each other.
Here class ‘A’ defines two attributes namely ‘a’ and ‘b’ of type integer and
access modifier as ‘protected’ while two methods namely ‘setDataA()’ and
‘displayA() which are public.
Class ‘B’ defines one attribute namely ‘c’ with access modifier ‘private’ and
two methods setDataB() and displayB() whose access modifier is public. Inheritance
and Polymorphism 97
Ownvkrng"kpjgtkvcpeg"
In multiple inheritance, a single subclass is derived from two or more
superclasses.
Jqy"vq"cejkgxg"ownvkrng"kpjgtkvcpeg"yjgp"kv"pggfA
When a developer needs to implement multiple inheritance as per the
demand of design of the system, instead of using class he can use interface. The
concept of interface is discussed in detail in section 3.6.
J{dtkf"kpjgtkvcpeg"⁄
In hybrid inheritance a combination of different types of inheritance can be
used. Following diagram explains how hybrid inheritance can be implemented:
Eqpegrv"qh"Rqn{oqtrjkuo
It is a Greek word derived from two words ‘poly’ means ‘many’ and
‘morphism’ means ‘forms’. It can be explained as ‘one thing having many forms’.
When applied to any programming language, in simple language, it can be
explained as ‘One Name which can be used in Various Forms’. Polymorphism
is very powerful concept of OOP language which helps to implement late
binding. Following programming constructs helps to implement polymorphism
1. Function Overloading
2. Member Overriding
3. Dynamic Binding(Virtual Functions)
These concepts adds more flexibility in program which helps developer to
make decision while runtime which is also known as dynamic binding. Binding
of the program takes place at two different levels – Static Binding and Dynamic
Binding. While binding, which can be resolved at compilation time is known as
static binding or early binding. Always static, final and private methods are
cannot be overridden. While in dynamic binding or late binding compiler does
not decide the method to be called. Member overriding is the best example of
dynamic binding. Following sub sections discusses all concepts in detail.
Hwpevkqp"qt"Ogvjqf"Qxgtnqcfkpi
The concept of function overloading helps developer to use same name for
different function blocks. The ambiguity while execution can be avoided by
differentiating every definition either by –
• Number of arguments passed
OR
• Type of arguments passed to function.
Pggf"qh"Hwpevkqp"Qxgtnqcfkpi"
In different situations we can prefer function overloading. The one situation
where there is need of writing function blocks where either process block is
similar but data type of arguments go on changing then we can use function
Inheritance overloading. For example programmer need to write a program to add two
102 and Polymorphism
“Only for Private Circulation”
numbers where user need to add either two integers or float or double values Java Programming
depending on his requirement. In case process is same for all function blocks,
while only data type goes on changing. In language like ‘c’, one need to write
functions as sumInt(int a, int b), sumFloat(float a, float b), sumDouble(double a, NOTES
double b) for adding integer, float and double respectively. But in java by using
concept of function overloading functions can be written as sum(int a, int b),
sum(float a, float b), sum(double a, double b). In case of function overloading
user of function need to remember only name of the function as ‘sum’ instead of
using different names for functions. It is shown in the following program –
/*Function overloading for different datatypes*/ class FunOverload
{
public static int sum(int a,int b)
{
[Link]("Function for Integers - "); int c=a+b;
return(c);
}
public static float sum(float a,float b)
{
[Link]("Function for Floats - "); float c=a+b;
return(c);
}
public static double sum(double a,double b)
{
[Link]("Function for Doubles - "); double c=a+b;
return(c);
}
public static void main(String arg[])
{
int s1=sum(5,3);
[Link]("Sum of Integers : "+s1); float s2=sum(5.6F,8.9F);
[Link]("Sum of Floats : "+s2); double s3=sum(5.67,8.93);
[Link]("Sum of Doubles : "+s3);
}
}
Output for the above program is shown in the command window given
Inheritance
below. Here function ‘sum’ has three definitions with different data types. In
and Polymorphism 103
Above program shows how same function names can be have different data
types for the arguments. Now we will see how we can differ arguments in number
of arguments.
/*Function overloading for different number of Arguments*/ class
FunOverloadNum
{
public static int area(int l,int b)
{
[Link]("Function for area of Rectangle - "); int c=l*b;
return(c);
}
public static int area(int s)
{
[Link]("Function for area of Square - "); int c=s*s;
return(c);
}
public static float area(float r)
{
[Link]("Function for area of Circle - "); float c=3.14f*r*r;
return(c);
}
public static void main(String arg[])
{
int ar=area(5,3);
[Link]("Area of Rectangle : "+ar); int as=area(5);
[Link]("Area of Square : "+as); float ac=area(5.6f);
[Link]("Area of Circle : "+ac);
}
Inheritance }
104 and Polymorphism
“Only for Private Circulation”
Above program defines three functions for calculating area for different Java Programming
shapes. The first function accepts two arguments for calculating ‘area of
rectangle’, while second accepts only one argument to calculate ‘area of square’.
Here the third definition of function ‘area’ again accepts one argument but of
type ‘float’, so that it will not be confused with function definition for ‘area of
square’. Output for the above program is shown below.
Qxgtnqcfkpi"Ogvjqfu"kp"c"Encuu"
Like normal functions, we can also overload methods in a class. While
defining a class we can define methods which shares same functionality, but
differ in either type or number of arguments, with same names but different
arguments. Following program explains method overloading in a class.
/*Method overloading in a class*/
class MethodOverload
{
private int i,j;
public void getData()
{
i=0; j=0;
}
public void getData(int a)
{
i=a; j=0;
}
public void getData(int a,int b)
{
i=a; j=b;
}
public void displayData()
{
[Link]("i = "+i+"\tj = "+j);
} Inheritance
and Polymorphism 105
Qxgtnqcfkpi"qh"Eqpuvtwevqtu"
In previous chapter we have discussed about the constructor, is a method
which helps in constructing an object on a class. Like other methods in a class,
it is possible to overload constructor in a class. In the previous section we have
seen how methods in a class can be overloaded. Following program demonstrates
overloading of constructor.
/*Constructor overloading in a class*/ class ConstructorOverload
{
private int i,j;
public ConstructorOverload()
Inheritance {
106 and Polymorphism
“Only for Private Circulation”
i=0; j=0; Java Programming
}
public ConstructorOverload(int a)
{
i=a; j=a;
}
public ConstructorOverload(int a,int b)
{
i=a; j=b;
}
public void displayData()
{
[Link]("i = "+i+"\tj = "+j);
}
}
class ConstructorOverloadImp
{
public static void main(String arg[])
{
ConstructorOverload obj1=new ConstructorOverload();
ConstructorOverload obj2=new ConstructorOverload(5);
ConstructorOverload obj3=new ConstructorOverload(50,70);
[Link]("For obj1 : ");
[Link](); [Link]("For obj2 : "); [Link]();
[Link]("For obj3 : "); [Link]();
}
}
The class ‘ConstructorOverload’ defines three constructors, from which one
is default constructor while two are parameterized constructor. Now user of the
class can initialize his object using one of these three options. First default
constructor initializes object members to zero. Second constructor initializes
object values with single value passed as an argument to the constructor. While
Third constructor accepts two different values from user and use to initialize the
object. How the object will be initialized depends on the use of constructor while
defining the object. In the program ‘obj1’ is defined using first default constructor Inheritance
and Polymorphism 107
Ogodgt"Qxgttkfkpi
The concept of member overriding is similar to member overloading. The
difference in these two is in member overloading more than one member with
same name are defined in same class definition. While in member overriding,
members having same name are defined in two different classes which are related
with each other through the relation of inheritance. Prerequisite for member
overriding is inheritance.
As discussed earlier, inheritance help to share members from predefined
class, known as super class, with its sub class. All protected and public members
from super class are available to its sub class, either within sub class definition
or outside the class using its object. For example if method ‘display’ is defined
in a super class as public, then sub class object can call method ‘display’ though
it is defined in its super class. While executing method ‘display’, though the
object is defined over sub class, method from super class is executed.
In method overriding sub class also defines members with same name as in
super class. Now, when sub class object calls method processor checks if sub
class has defined it, if so it executes method from sub class itself and not from
super class.
Following program demonstrates method overriding.
/*Method Overriding demonstration through inheritance*/ class SuperClass
{
public void method1()
{
[Link]("Method1 from Super class");
}
public void method2()
{
[Link]("Method2 from Super class");
Inheritance }
108 and Polymorphism
“Only for Private Circulation”
} Java Programming
class SubClass extends SuperClass
{
public void method2()
{
[Link]("Method2 overrides method2 from Super Class");
}
}
class MethodOverridingImp
{
public static void main(String arg[])
{
SuperClass objSuper=new SuperClass(); SubClass objSub=new SubClass();
[Link]("For object on Super Class : "); objSuper.method1();
objSuper.method2();
[Link]("For object on Sub Class : "); objSub.method1();
objSub.method2();
}
}
In the above program defines three classes, ‘SuperClass’, ‘SubClass’ and
‘MethodOverridingImp’. From these three classes ‘SubClass’ is derived from
class ‘SuperClass’.
‘SuperClass’ defines two member methods named as ‘method1’ and
‘method2’ which are ‘public’. Class ‘SubClass’ which is derived from
‘SuperClass’ defines one method ‘method2’. The public members from super
class are accessible to object on sub class, hence both methods from super class
are accessible to object on sub class.
In function ‘main’ one object for each class ‘SuperClass’ and ‘SubClass’
are defined. ‘objSub’ object, object on class ‘SubClass’, calls two methods
‘method1’ and ‘method2’. When object calls ‘method1’, which is defined with
‘SuperClass’ gets executed. For ‘method2’, now processor has two options one
from ‘SuperClass’ and one from its own. But here preference is given to its own
method. Hence we say that ‘method2’ from ‘SubClass’ overrides ‘method2’ from
‘SuperClass’. Output for the program is shown in command window below.
Inheritance
and Polymorphism 109
F{pcoke"Ogvjqf"Fkurcvej"*FOF+
Dynamic Method Dispatch, also known as virtual functions, can be
considered as the next step of method overriding. While implementing the
concept, methods from different classes are executed by using a reference to the
superclass. When one needs to implement DMD, all the classes need to have
hierarchical inheritance. In simple words, all classes should be derived from a
single Superclass. Reference to this superclass is used to call methods
dynamically from different classes. DMD is the real example of dynamic binding
where which method is to be executed is not known while compilation time, but
is decided at runtime.
A method that is commonly defined in all classes is executed using
reference. A reference to the class only points to an object. Already we have
discussed the concept of ‘reference’ while defining an object for a class, in
chapter 2. Reference for a superclass can point to object for the class as well as
to the objects defined on its derived classes also. Thus using reference to their
superclass own methods can be executed. The concept of DMD is shown in the
following program.
/*Method Overriding demonstration through inheritance*/ class SuperClass
{
public void method1()
{
[Link]("Method1 from Super class");
}
public void method2()
{
[Link]("Method2 from Super class");
}
}
class SubClass1 extends SuperClass
{
public void method2()
{
Inheritance
110 and Polymorphism [Link]("Method2 from SubClass1, overrides method2
Mg{yqtfu"Wugf"kp"Kpjgtkvcpeg"cpf"Rqn{oqtrjkuo
i) abstract – It is a keyword in java that can be used with the class or a
method in a class. In some situations, the user may need to define
classes that should not be instantiated, but for defining some common
characteristics the class is defined. Then the class is defined as
‘abstract’ class. The abstract class is used as a superclass for the classes
which need to share these common characteristics. The following
program explains the use of the ‘abstract’ keyword.
/*Abstract Class in inheritance*/ abstract class SuperClass
{
public void method1()
{
[Link]("Method1 from Super class");
}
}
class SubClass1 extends SuperClass
{
public void method2()
{
[Link]("Method2 from SubClass1");
}
}
class SubClass2 extends SuperClass
{
Inheritance public void method1()
112 and Polymorphism
“Only for Private Circulation”
{ Java Programming
[Link]("Method1 from Sub class2, overrides method1 from
Super Class");
}
public void method2()
{
[Link]("Method2 from SubClass2");
}
}
class AbstractClass
{
public static void main(String arg[])
{
//SuperClass objSuper=new SuperClass(); SubClass1 objSub1=new
SubClass1(); SubClass2 objSub2=new SubClass2();
[Link]("Object for SubClass1 : "); objSub1.method2();
objSub1.method1(); [Link]("Object for SubClass2 : ");
objSub2.method2();
objSub2.method1();
}
}
The above program defines two subclasses ‘SubClass1’ and
‘SubClass2’ which are derived from an abstract superclass
‘SuperClass’. Here superclass is an abstract class and hence it cannot
be instantiated. If the user tries to define an object on an abstract class
compiler gives compilation error which is shown in the command
window below.
The keyword ‘abstract’ also can be used with the method in an abstract
class. When a method is defined as an abstract method, it will give
only its signature in class, is compulsorily implemented by its derived
classes. The following program shows the use of the abstract method
in the abstract class.
/*Use of Abstract Method in Abstract Class in inheritance*/ abstract class
SuperClass
{
public void method1()
{
[Link]("Method1 from Super class");
}
abstract public void method2();
}
class SubClass1 extends SuperClass
{
public void method2()
{
[Link]("Method2 from SubClass1");
}
}
class SubClass2 extends SuperClass
{
public void method1()
{
iii) super – Inheritance helps to relate two classes where protected and
public members from super class are accessible to sub class definition.
Within subclass definition members from super class needs to be
accessed from processing. The keyword ‘super’ helps in accessing
super class members within sub class definition.
The keyword ‘super’ is used with two different contexts. It can be used
as an object or as a method (constructor). When ‘super’ is used as
object, it is used along with ‘.’ (dot operator), while using super as a
method (constructor from super class) is used with brackets. Use of
‘super’ keyword is demonstrated with the help of following program.
/*using super keyword for accessing members from super class*/ import
[Link].*;
class SuperClass
{
protected int i;
public SuperClass(int a)
{
i=a;
}
public void getData()
{
Scanner s= new Scanner([Link]); [Link]("Enter Value for i :
"); i=[Link]();
Inheritance
118 and Polymorphism }
Kpvgthceg
Interface is a kind of class which cannot be instantiated i.e. an object cannot
be declared on an interface, but it can be implemented by other classes using
inheritance. Interface allows user to fully abstract a class which can be
implemented using multiple inheritance.
Fghkpkpi"Kpvgthceg
Interface is defined using keyword interface. The syntax for defining
interface is as given below-
<access modifier> interface <interface name>
{
< member methods and attributes>;
}
The interface definition starts with ‘access modifier’. Access modifier is
either public or not to be mentioned. It defines access of interface. If the access
modifier is not given the interface is accessible within package in which it has
been defined, but the public access gives public access to interface.
The ‘interface’ keyword starts definition of an interface class which cannot
be instantiated but can be implemented by other classes by deriving it. Every
interface like classes has member methods and member attributes. Member
methods in an interface are abstract methods defined without definition hence
syntax for definition of member methods ends with ‘;’, as shown in syntax below.
Inheritance
120 and Polymorphism
“Only for Private Circulation”
<return data type><method name>( <parameter data type list> ); Java Programming
While the member attributes are final attributes and need to be assigned
with value, which is fixed while implementation and cannot be changed during
use. The syntax for definition of member attributes is given as-
<data type> final <member name> = <value> ;
All members in interface are implicitly public and static. Following code
demonstrates how a interface can be defined –
interface Shape
{
static final float pi=3.14F;
void getData(); void setData(int s);
void setData(int a,int b); void area();
void perimeter(); void display();
}
Above given code defines an interface with name ‘Shape’. As an interface
it defines one data member which is assigned with a final value and is of type
float, whose value cannot be changed. While other are signatures for the methods
‘getData’, ‘area’, ‘perimeter’, ‘display’ and the overloaded method ‘setData’. All
methods are defined with number and type of arguments and return data types.
While implementing interface ‘Shape’, the class need to implement all these
methods as per their signatures. If any method from interface class does not want
to implement then it can be defined with empty block.
After defining an interface user can compile the interface to create its
bytecode. And whenever need to implement the interface, by importing the
package the interface can be implemented by the class.
Wukpi"Kpvgthceg
Once defined interface can be implemented by any number of classes. To
implement an interface clause ‘implements’ is added with the class definition.
The class which implements interface needs to implement all methods from an
interface. Syntax for implementation of interface while defining class is given
as –
class <class name> [extends <superclass>] [implements <interface1>,
<interface2>, …]
{
<members from class>
}
Inheritance
and Polymorphism 121
Kpvgthceg"cpf"Encuu
In the previous chapter we have discussed class in detail, and in this section
we have discussed interface in detail. From the discussion we can conclude that
a class can be instantiated while an interface cannot. For a class user can define
an object, which can occupy memory and can store and process data. But, on the
other hand, for an interface it is not possible. For an interface an object cannot
be created and hence cannot store or process data. We can use interface only by
implementing it through a class. If we try to declare an object for an interface it
gives a compilation error. The error is demonstrated with the help of following
program.
interface Shape
{
static final float pi=3.14F; void getData();
void setData(int s);
void setData(int a,int b);
void area();
void perimeter(); void display();
}
class InterImp
{
public static void main(String arg[])
{
Shape objs=new Shape();
}
} Inheritance
and Polymorphism 125
Cfxcpvcigu"qh"flkpvgthceg‚"qxgt"flcduvtcev"encuu‚"cpf"flcduvtcev"ogvjqf‚
The usage of abstract class and interface are similar, but any subclass cannot
be extended from more than one abstract class but any subclass can implement
more than one interface.
The abstract class can implement methods defined in it, hence if its subclass
does not implement the method, method from super class is executed. While
methods from interface needs to be implemented by the class who implements
the interface.
*****
Inheritance
126 and Polymorphism
“Only for Private Circulation”
Java Programming
UNIT - 4
CONCURRENT PROGRAMMING
Ejcrvgt"Qdlgevkxgu"
To understand –
o Multitasking Programming and Threading
o Thread Synchronization
Eqpegrv"qh"Ownvkvcumkpi"cpf"Vjtgcfu
When a sequential process is being executed, it is assigned to a processor
and depending on its requirements processor goes on allocating resources to it.
Hence the processor is busy with the single process till it does not end. This is
known as Single Tasking.
With the development of multi core high speed processors the operating
systems became multitasking. In multitasking different processes reside in
memory and user can easily switch among processes. Like two different
applications like command window and notepad are open at the same time and
user can switch between these two applications. Some processes may be executed
simultaneously, which is achieved with parallelism. For example in background
some downloading is in progress, while in foreground user is editing some file.
In short, executing more than one process at a single time is known Multitasking
Programming. Multitasking programming can be achieved with two different
concepts –
• Process Based Multitasking
• Thread Based Multitasking
In process based multitasking two different independent processes are being
executed. These processes has their own space and own data. They do not share
any data among each other. This type of multitasking is controlled by operating
system, and programmer does not have any control on it.
While in thread based multitasking a single process is divided into small
independent units or sub- processes referred as ‘thread’. The multithreaded
program shares same memory, as it is anyhow a single process, and therefore
data can be shared among different threads. Programmer can control the
execution of threads. The concept of multi core processor has given rise to the
concept of threads. Here thread can be seen as threads working with a single
puppet to move its different parts simultaneously. In programming, while
Concurrent
implementing the concept of parallelism, a single program is divided in multiple
Programming 127
Ownvkvjtgcfkpi"kp"lcxc
Java as a powerful programming language developed for network
programming, multithreading is one of its key characteristic. The package
‘[Link]’ defines classes and interfaces required for multithreading
programming. As discussed earlier ‘[Link]’ is the package which provides
basic functionalities required for writing program. So java provides thread as a
basic concept in programming, and to implement it programmer does not need
to take any extra efforts. In this chapter we are going to discuss about how we
can write programs supporting multiple threads.
Lifecycle of Threads [[Link] [[Link]]
Before writing programs implementing threads, we need to understand the
lifecycle of the thread. As thread is defined as a lightweight process, like every
process, it also needs to work in different states. States through which and
according to which execution of thread is defined, defines its lifecycle.
Java defines four basic states for a thread. When a thread is defined, it can
be in one of the four states. For every state its behavior can be defined. These
four 4 states in thread life cycle in java are ‘new, runnable, non-runnable or
blocked and terminated’. In addition to these four states, for better understanding
of lifecycle of thread we can add some more states like ‘waiting, timed-waiting’.
These different states are defined with help of different abstract methods which
are overridden by the implementing class. JVM controls different threads being
executed through these methods. All these states are explained as follows–
• New
A thread that is just instantiated is in new state. When a start() method
is invoked, the thread moves to the ready state from which it is
automatically moved to runnable state by the thread scheduler.
• Runnable (ready_running)
A thread executing in the JVM is in running state.
Concurrent
128 Programming
“Only for Private Circulation”
• Non-Runnable (Blocked) Java Programming
A thread that is blocked waiting for a monitor lock is in this state. This
can also occur when a thread performs an Input / Output operation and
moves to next (runnable) state.
• Waiting
A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.
• Timed_Waiting (sleeping)
A thread that is waiting for another thread to perform an action for up
to a specified waiting time is in this state. The thread from runnable
state can move to sleeping state by invoking sleep() method.
• Terminated (dead)
A thread that has exited is in this state. With the completion of
execution of run() method the thread is terminated.
Etgcvkpi"Vjtgcfu
Though java provides thread technique as a basic functionality defined in
‘[Link]’, we need to make aware to processor of different thread, otherwise
the process will be executed as a single thread. For the purpose java provides
two methods to create threads in a program by using– Concurrent
Programming 129
Vjtgcf"Encuu
Class ‘Thread’ is defined in package ‘[Link]’. When programmer uses
threads, the class is derived from class ‘Thread’. Its syntax is shown below –
class <class name> extends Thread
{
/*Member definitions*/
}
Here programmer’s class is now sub class of class Thread. Hence members
from class Thread can be overridden by the programmer. The object defined on
the class is a threaded object and can be executed simultaneously with other
threads. This object is not like a normal class object and hence we need to execute
it differently. A threaded object needs to be assigned with the process which will
be executed without any interruption. This process can be defined by overriding
the abstract method ‘run( )’ in threaded class. Along with all members in a class
we can override a method ‘run( )’ which will change state of a thread from new
to ‘runnable’. Thus the thread class definition changes as –
class <threaded class name> extends Thread
{
/*Other member definitions*/ public void run()
{
/*Instructions to be executed as a process for thread*/
}
}
So now it can be observed that the threaded class definition has added with
a method ‘run( )’. The method run is responsible for defining the process which
will be executed as a thread.
The thread execution starts through threaded class object, which invokes
the ‘start()’. Method start is a method defined in class ‘Thread’, which is
responsible for starting execution of thread. When the method is called using
threaded class object, JVM calls method ‘run( )’ from threaded class. It syntax is
given below –
Concurrent
130 Programming
“Only for Private Circulation”
class < threaded class name> extends Thread Java Programming
{
/*Other member definitions*/ public void run()
{
/*Instructions to be executed as a process for thread*/
}
}
class <implementation class name>
{
public void main(String arg[])
{
/*Define object on threaded class*/
<threaded class name><object name> = new <threaded
class name>;
/*Starting with thread execution*/
<object name>.start();
}
}
The above declarations can be understood better with the help of following
program –
/*defining and executing thread*/ class ThreadTrial extends Thread
{
public void run()
{
[Link]("Thread Execution Started");
}
}
/*Thread Implementation class*/ class ThreadImp
{
public static void main(String argv[])
{
ThreadTrial objTh=new ThreadTrial(); [Link]();
}
}
Concurrent
Programming 131
Concurrent
132 Programming
“Only for Private Circulation”
Java Programming
Twppcdng"Kpvgthceg
Other method to implement threads in our program is to implement interface
‘Runnable’. In this method instead of extending the class, whose object is to be
executed by thread, it implements interface. In the subsection we will discuss
sequence of steps for implementing Runnable interface.
The package [Link] defines this interface. The interface ‘Runnable’
defines the method ‘run’, which is to be overridden by the class implementing
interface.
Concurrent
Programming 133
The above syntax shows how a user defined class can implement the thread.
The class definition starts with the keyword ‘class’ followed by ‘class name’ like
a normal class definition, but is followed by the keyword ‘implements’ and the
interface name ‘Runnable’. Implementation of interface ‘Runnable’ avails the
definition of the method ‘run’ to start with the thread process. The class can define
its own members along with the method definition for method ‘run’. The method
‘run’ defines, as discussed earlier while discussing class Thread, process to be
executed by thread.
The thread defined by the class can be executed through instance on class
Thread. Here the Thread object needs to be linked with object or reference class
implementing ‘Runnable’ interface to its object. So here to execute thread we
need two objects. One is for implementing class and one for class ‘Thread’. The
Thread class object needs reference to the implementing class object. Therefore
while declaring ‘Thread’ object parameterized constructor is used accepting
reference for implementing class object. Syntax for the for declaring and linking
class ‘Thread’ object is given below –
<class name><object name> = new <class name>( );
Thread <thread object name> = new Thread(<object name>);
Here <class name> is name of the class which implements ‘Runnable’
interface and <object name> is name of the object on implementing class. Same
object’s reference is passed as argument to constructor for Thread object.
Following code explains how to use ‘Runnable’ interface.
/*defining and executing thread using Runnable interface*/ class
RunnableTrial implements Runnable
{
intthid;
Concurrent publicRunnableTrial(int i)
134 Programming
“Only for Private Circulation”
{ Java Programming
thid=i;
}
public void run()
{
[Link]("Thread"+thid+" Execution Started
usingRunnableinterface ");
}
}
/*Thread Implementation class*/ class RunnableImp
{
public static void main(String argv[])
{
RunnableTrialobjRun=new RunnableTrial(1); Thread objTh= new
Thread(objRun); [Link]();
}
}
Above code defines two classes – first is the class which implements
‘Runnable’ interface to define thread, named ‘RunnableTrial’, while other to
execute thread named ‘RunnableImp’. The class ‘RunnableTrial’ defines a
parameterized constructor and overrides method ‘run’ from interface ‘Runnable’.
The class ‘RunnableImp’ executes thread using an object on class ‘Thread’
referencing to object on class ‘RunnableTrial’. Therefore firstly object on class
‘RunnableTrial’ (objRun) is created, whose reference is passed to thread object.
The object on class ‘Thread’ is created using constructor accepting object
reference as a parameter. After declaration of objects the thread execution is
started using method ‘start()’ from class ‘Thread’ which executes ‘run()’ method
from class ‘RunnableTrial’. Output for the following program is shown below –
Vjtgcf"encuu"Xu"Twppcdng"Kpvgthceg
Above subsections has discussed about two different methods for threading.
Both, the class and the interface, help to implement thread mechanism in
program. Now it is need to discuss their advantages and disadvantages over each
other. Concurrent
Programming 135
Vjtgcf"U{pejtqpk|cvkqp"<"Kpvtqfwevkqp
When more than one thread are sharing same resources, like data, memory
or input/output devices, we need to stop this parallel execution and make other
threads to wait till active thread completes its task so that proper output for the
program can be given. This is known as ‘Synchronization of Threads’.
Java provides a keyword ‘synchronized’ which helps in synchronizing
threads. The keyword can be used at two different levels –
• For a member method – Methods in class can be declared as
synchronized methods. A class for which multiple threads may be
defined, for methods of the class ‘synchronized’ keyword can be
applied. From the class if any method which uses sensitive resource
and if executed parallel mwy generate erroneous results can be defined
with synchronized keyword. Syntax used to define a method as
‘synchronized is given as –
<access modifier> synchronized <return type><method
name>(<arguments>);
• A block in ‘run’ – In run method also we can write the process block
Concurrent
136 Programming within ‘synchronized’ block. A set of instructions or call to methods
Here we have executed two threads, but as both are sharing same data,
output for ‘display’ is same for both threads.
You can check the output by removing synchronized keyword, check what
happens.
***** Concurrent
Programming 139
UNIT - 5
JAVA INPUT / OUTPUT
Ejcrvgt"Qdlgevkxgu"
To understand –
o What is Stream?
o Types of Streams
o Input/output in java
Eqpegrv"qh"Uvtgcou"]jvvr<11kkvk0ce0kp_
Like any other programming languages, java also defines functionalities for
basic input and output. For the purpose java provides two packages. First package
deals with console input and output while the second package for developing
GUI (Graphical User Interface), which defines different components for
accepting input and output. In short java provides three types of I/O operations
• Console Input /Output
• File Input / Output
• GUI Input / Output
A stream can be understood as a sequence of objects that supports various
methods which can be pipelined to produce the desired result. A stream is linked
to a physical device by the Java I/O system. As the all streams behave in same
manner, the same I/O classes and methods can be applied to any type of device.
For example the input may come from different sources like, it may be from file
on a disk or may be from keyboard or from a network socket, but the stream does
not [Link] means an ‘input stream’ can abstract many different kinds
of input. Likewise, an output stream may refer to the console, a disk file, or a
network connection. So streams only deals with input and output being ignorant
of source or destination. Java implements streams within class hierarchies defined
in the [Link] package. The class hierarchy defined in java package is shown in
following image -
V{rgu"qh"Uvtgcou
Streams can accept input or gives output using two basic types –
• Byte Streams
• Character Streams
These two types defines data represention using streams. Previously in
earlier versions of java was having only ‘byte stream’, but later on one stream
type was introduced for reading characters, known as character stream. Both
these streams are discussed in following subsections. At the system level still
byte stream is used, character stream is to add efficiency for handling characters.
D{vg"Uvtgcou
As the name suggests byte stream reads data in binary format. In hierarchy
for byte stream InputStream and OutputStream are two abstract classes at very
super level. These abstract classes have several concrete subclasses. These
subclasses are responsible for handling differences between various
[Link] classes are available in ‘[Link]’ package, and can be used after
importing this package. Mostly these classes are used to read data from disk files
and network connections. The most used methods used for byte streams are read(
) and write( ). These are abstract methods defined in classes InputStream and
OutputStream, which are overridden by their subclasses and creates a unique
environment for all streams.
Ejctcevgt"Uvtgcou
The class hierarchy for character stream defines two super classes, Reader
and Writer. These are the abstract classes designed to handle Unicode. These
classes define abstract methods which are overridden by their subclasses. ‘read(
)’ and ‘write( )’ methods are commonly used to read and write characters
respectively. Methods with same name are defined with byte streams also, and
this brings uniformity in both streams. These stream definitions are best examples
of dynamic method dispatching.
Kprwv"Qwvrwv"Jkgtctejkgu
While writing java program, if the program is using basic instructions, we
don’t need to import any package. The program itself imports ‘[Link]’ package
automatically. The package ‘[Link]’ defines all basic classes for example
Java Input / Output 141
U{uvgo
‘System’ class is defined in package ‘[Link]’. The class ‘System’ defines
various data members and methods which are helpful in satisfying basic system
related requirements of the programmer. For example to read current date and
time etc. The method for garbage collection ‘gc()’ is defined in class ‘System’.
When user want to terminate the program before completing its execution the
method used is ‘exit()’, it is also defined in class System. The functionalities
related with time, currency, copying a part of one array to other all such basic
functionalities which user may need to use as basic functionalities are defined
with class System.
Along with these members the class also defines three stream variables, ‘in’
for referring to standard input, ‘out’ to refer standard output and ‘err’ to refer to
standard error stream. All these variables are public and static and hence without
using object on class System we can use these variables.
U{uvgo0qwv
As discussed in previous sub-section ‘out’ is public static member defined
as instance on ‘[Link]’ in class ‘System’. ‘out’ always refers to
standard output stream. Most of the times it is console. When programmer want
togive message on console then using ‘print()’ or ‘println()’ method from class
‘PrintStream’ is used. Use of these methods we have already discussed in chapter
1, while discussing output.
U{uvgo0kp
Like ‘out’, ’in’ is an instance define on ‘InputStream’ class. It is a public
static member and is accessed through ‘System’ class. The object ‘in’ always
refers to standard input, which is a keyboard by default. The object helps to read
input from keyboard. In next sections when we will discuss about keyboard input,
objects defined on ‘Scanner’ is initialized with the object ‘[Link]’.
U{uvgo0gtt
[Link] refers to the standard error stream and an instance on class
‘PrintStream’. The object helps to print standard error.
Kprwv"Uvtgco
InputStream class is the superclass of all input classes. Itdeals with input
operations from input source through byte stream. As discussed earlier while
accepting input using keyboard we need to use object ‘in’ which an instance of
class InputStream. Other than keyboard, class InputStream and other different
142 Java Input / Output
“Only for Private Circulation”
classes derived from it helps to accept input from various sources without any Java Programming
realization of internal complexities.
Qwvrwv"Uvtgco"encuu
The [Link] class is the superclass of all classes representing
an output stream of bytes. An output stream accepts output bytes and sends them
to some sink.
Hkng"encuu
‘InputStream’ and ‘OutputStream’ are classes defined to deal with input
output of data through standard devices like keyboard and monitor. But when we
need to read and write data from or to file ‘File’ class in java helps. The File class
is Java’s representation of a file or directory path name. When in java there is
need to handle a file class ‘File’ is instantiated. The instance/object created on
file refers to the memory space where the file is stored temporarily. It also helps
in reading and writing data from file. Actually the object not only stores data
about file but also about location of file on external storage [Link] also provides
different methods which helps in processing on file location.
Syntax for defining object on class ‘File’ is given as below –
File <object name> = new File(String <filepath>);
Constructor in class file is overloaded, and hence an object on class ‘File’
can create with different methos. In the above syntax mostly used process for
creation of object for class ‘File’ is given. In the above syntax we have called
the constructor which accepts one argument of type ‘String’. Here String may
be file name, if it stored in the same folder, or otherwise it may be path. Following
code shows how to create ‘File’ object.
File fRef = new File(“Trial”);
Above instruction either creates (if not existing) or retrieves (if existing)
file with name “Trial”. The object created on class ‘File’ named as ‘fRef’ refers
to current file location and stores all details about file “Trial”.
Tgcfgt"encuu
It is an abstract class defined in package ‘io’ which is used as a super class
for all classes based on character stream. As we have discussed earlier java
defines two different hierarchies one for byte stream and other for character
stream. Earlier discussed classes are used for byte stream, while the class
‘Reader’ defines new hierarchy for character stream. It defines method to read
so that any class overriding method ‘read()’ can use it in any format.
Ytkvgt"encuu
Like class ‘Reader’ it is a super class for all classes in hierarchy supporting
character stream. The class defines basic output methods those all are
implemented by the classes in hierarchy. One of the mostly used method is
‘write()’.
Java Input / Output 143
ß Hkng"Tgcfgt
FileReader is useful to read data in the form of characters from a ‘text’
[Link] class inherit from the InputStreamReader Class. The constructors of this
class assume that the default character encoding and the default byte-buffer size
are appropriate. To specify these values yourself, construct an InputStreamReader
on a [Link] is meant for reading streams of characters. For
reading streams of raw bytes, consider using a FileInputStream.
Following program demonstrates how a file can be read using ‘FileReader’
// Demonstrate FileReader. import [Link].*;
classFileReaderDemo
{
public static void main(String args[]) throws Exception
{
FileReaderfr = new FileReader("[Link]"); BufferedReaderbr
= new BufferedReader(fr);
String s;
while((s = [Link]()) != null)
{
[Link](s);
}
[Link]();
}
}
The above program uses object on class ‘FileReader’ which throws
‘IOException’ which need to be handled and hence we define main as ‘throws
Exception’. ‘fr’ is an object on class ‘FileReader’ which executes constructor
accepting file name as an argument. The constructor opens file for reading. The
object ‘fr’ now refers to file and store entire details for file which are needed for
processing file. For reading data from file we have used ‘BufferedReader’ object
which helps in reading data using buffer. The ‘BufferedReader’ constructor
accepts reference to ‘FileReader’ object, as here the source for reading data is
file.
144 Java Input / Output
“Only for Private Circulation”
Java Programming
ß Hkng"Ytkvgt
Class ‘FileWriter’ is used to create a text file. This class is subclass of the
class‘OutputStream’.The constructors of this class assume that the default
character encoding and the default byte-buffer size are acceptable. The
constructor on ‘FileWriter’ accepts file name as an argument which is created if
not existing, otherwise is overwritten. Following program demonstrates use of
‘FileWriter’ class.
// Demonstrate FileWriter. import [Link].*;
classFileWriterDemo
{
public static void main(String args[]) throws Exception
{
String source = "Welcome to the world of java file"; char buffer[] = new
char[[Link]()]; [Link](0, [Link](), buffer, 0); FileWriter
f = new FileWriter("[Link]");
for (int i=0; i <[Link]; i ++)
{
[Link](buffer[i]);
}
[Link]();
}
}
In the above program ‘buffer’ is defined as a character array, which is acting
as a buffer and helps in reading one by one character. ‘f’ is an object on class
‘FileWriter’ which refers to file ‘[Link]’. ‘for’ loop helps in reading character
by character from buffer and the method ‘write’ writes the character to the file
referred by object ‘f’. Following command window shows output for above
program.
Java Input / Output 145
Hkng"Kprwv"Uvtgco
File Input Stream is useful to read data from a file in the form of sequence
of bytes. FileInputStream is meant for reading streams of raw bytes such as image
data.
//Reaing Data from file import [Link].*;
classReadFromFile
{
public static void main(String[] args) throws IOException
{
File f=new File("[Link]"); int c;
FileInputStreamfis=new FileInputStream(f); while((c=[Link]())!=-1)
[Link]((char)c); [Link]();
}
}
The program’s output is same as program for ‘FileReader’. But here
‘FileInputStream’ uses byte stream, and more useful for other type of files which
stores data in binary format than text files.
Hkng"Qwvrwv"Uvtgco
File Output Stream is meant for writing streams of raw bytes such as image
data. In such situations, the constructors in this class will fail if the file involved
is already open.
//Writing Data to file import [Link].*; class WriteTOFile
{
public static void main(String[] args) throws IOException
{
Ugtkcnk|cvkqp
In some situations where we need to convert the data in object to byte
stream, where object is an instance on user defined class, or vice a versa then an
interface in ‘[Link]’ package named ‘Serializable’ is used. Mostly ‘Serializable’
interface is used when objects need to be transferred from one node to another
on network or to write an object to file. As against to ‘Serializable’, the byte
stream is deserialized which converts byte stream to corresponding object.
Deserialization is used to read object from file, as it is read as byte stream and
need to be converted to corresponding object, or when byte stream is received to
destination node it again need to be converted to corresponding object.
When one need to convert object to byte stream and byte stream to object
interface ‘Serializable’ is implemented. If the super class implements
‘Serializable’ sub class need not implement it. Following program explains use
of interface ‘Serializable’.
//Using Serializable interface to write and read object to and from file import
[Link].*;
class Student implements Serializable
{
private String name,course; public Student()
{
name="";course="";
}
public Student(String n,String c)
Java Input / Output 147
Dwhhgtgf"Uvtgcou
Buffer is an internal memory which can be described as array of bytes. It is
a temporary storage used in between the real stream and program variable. For
example while reading data from file, every time we read data of same length
which can be hold by variable and assign it to that variable. We process the data
in variable and again control goes to file stream to read next data. Here while
every time reading data from file a call to OS is generated, which becomes more
time consuming. Instead of this if we add a buffer between file and variable,
where size of buffer is large as compared to variable size. Once the buffer is
added, large size of data which can be accommodated in buffer is read from file
stream and is kept with buffer. Whenever, now read operation is to be carried out
instead of generating system call, now data is directly available in buffer. The
read operation on buffer is carried out till buffer is not empty.
Java defines ‘BufferedInputStream’ and ‘BufferedOutputStream’ for reading
and writing from and to buffer respectively.
Dwhhgtgf"Kprwv"Uvtgco"]jvvr<11lcxcfkhh0uqwteghqtig0pgv_
A ‘BufferedInputStream’ adds functionality to another input stream-namely,
the ability to buffer the input and to support the mark and reset methods. When
the BufferedInputStream is created, an internal buffer array is created. As bytes
from the stream are read or skipped, the internal buffer is refilled as necessary
from the contained input stream, many bytes at a time.
Dwhhgtgf"Qwvrwv"Uvtgco
[Link] class implements a buffered output stream.
By setting up such an output stream, an application can write bytes to the
underlying output stream without necessarily causing a call to the underlying
system for each byte written.
Dwhhgtgf"Ytkvgt"]jvvru<11yyy0iggmuhqtiggmu0qti_
UNIT - 6
JAVA APPLETS AND GUI
Ejcrvgt"Qdlgevkxgu"<
To understand –
o What isApplet?
o Creating Simple Applet
o AppletLifecycle
o Concept ofAWT
o AWTcontrols
Crrngv"Eqpegrv
One of the major characteristics of Java Programming Language is to
support Internet Technologies and was found to be powerful as Network
Programming Language. Initially the language started its network programming
with ‘Applets’. In this chapter we are discussing about ‘Java Applets’. ‘Java
Applets’ are one of the popular application development tools for network. The
technology helps to develop small applications which executes as a part of web
document on internet server. Java from the scratch of development is worried
about security of resources on which the application is being executed. Applets
are executed on client’s machine with limited access to resources on client
machine. Hence it executes without introducing the risk of viruses or breaching
data integrity. While adding security features to applet technology it has given
rise to some drawbacks, because of which it has become outdated technology
and new versions of browsers do not support applets. Following points discuss
what developers cannot achieve using applets –
• An applet cannot read, write data on and from client’s machine and hence
cannot store any data permanently on client’s machine.
• It cannot call any program from client’s machine.
• It cannot discover any information about user from client’s machine like
user name or password.
• It cannot open network connections other than server from which the
applet is loaded.
In next sections we will see how we can develop and use applets to develop
internet applications.
Java
Applets and GUI 153
Crrngv"Crrnkecvkqp"⁄
Firstly we will see structure of simple applet application shown in following
table, which is saved with extension ‘.java’.
/*Import necessary packages required to execute applet */ import [Link].*;
[Link].*;
/*start applet extension of class Applet*/
public class <Applet Class Name> extends Applet
{
public void paint(Graphics g)
{
/*Code to execute an applet*/
}
}
Above code gives syntax for developing a small and simple applet
application. An applet application starts with import statement. While designing
an applet we need to import minimum two packages, which make us available
necessary classes required to develop a minimum applet.
Java
154 Applets and GUI
“Only for Private Circulation”
The first package is ‘[Link]’, which helps us to develop GUI for Applet. Java Programming
The second package is ‘[Link]’ which avails class ‘Applet’, used as
super class for our applet application. Every applet application is supposed to be
sub class of class ‘Applet’. Derivation of class ‘Applet’ is shown in figure given
below –
80304"cpf"803050
After ‘import’, definition of applet application starts. The applet application
class is always defined as ‘public’, so that the class definition will be publically
accessible to external applications like ‘html’ code file or appletviewer. It is
followed by the keyword ‘class’ and class name for the applet application. The
class name is nothing but applet application name. As discussed above we need
to define applet application class as sub class of class ‘Applet’. The class extends
system class ‘Applet’, so class name is followed by ‘extends Applet’, so that all
methods from class ‘Applet’ are available to user.
The class definition defines processes for applet application which is
implemented through different overridden methods from class ‘Applet’. Every
applet application starts execution from method ‘paint()’, which is same as
‘main()’ method in any java application. Applet can override methods from class
‘Applet’, which helps to add processes to be executed depending on its life state
like ‘init()’, ‘start()’ and many more.
Java
Applets and GUI 155
Vjg"vci"flcrrngv‚"ku"wugf"ykvj"vjtgg"cvvtkdwvgu"⁄
Code – Value of attribute is the class name of an applet application. Width
– It is assigned with the initial width of an applet application. Height – It is
assigned with the initial height of an applet application.
If developer wishes to run an applet using appletviewer application, in case
same HTML code is embedded in ‘.java’ file within comments. These html tags
are not known to the java compiler hence html code is written within comments
as non-executable code. Appletviewer application can execute this commented
code and can execute the application. The format to add HTML code in ‘.java’
file of an applet is shown in following block –
/*Import necessary packages required to execute applet */ import
[Link].*;
[Link].*;
/*HTML code for appletviewer*/
/*<html>
<body>
<applet code="AppletClassName" width=200 height=60>
</applet>
</body>
</html>*/
/*start applet extension of class Applet*/
public class <AppletClassName> extends Applet
{
Java
156 Applets and GUI public void paint(Graphics g)
k0 Crrngv"Crrnkecvkqp"wukpi"Dtqyugt
Following program shows a simple applet application with name
‘WelcomeApplet’. The first block is code for applet while in second block code
for html file is given. Explanation for the code is given below code.
import [Link].*; import [Link].*;
public class WelcomeApplet extends Applet
{
public void paint(Graphics g)
{
[Link]("Welcome to the world of Applet", 20, 20);
}
}
As discussed earlier firstly we import two packages, package ‘awt’ and
package ‘applet’, ‘awt’ helps to interact with user using GUI while ‘applet’ avails
class ‘Applet’ definition.
The next line in the program declares the public class ‘WelcomeApplet’,
hence the file is saved with name ‘[Link]’. Inside WelcomeApplet,
paint( ) is declared. ‘paint( )’ is called each time to redisplay its output. The paint(
) method has one parameter of type Graphics. This parameter contains the
graphics context, which describes the graphics environment in which the applet
is running. This context is used whenever output to the applet is required.
Inside paint( ) is a call to drawString( ), which is a member of the Graphics
class. This method outputs a string beginning at the specified ‘x, y’ location. It
has the following general form:
xqkf"ftcyUvtkpi*Uvtkpi"oguucig."kpv"z."kpv"{+
Here, message is the string to be output beginning at x,y which represents
coordinates of output screen. In a Java window, the upper-left corner is location
0,0. The call to drawString( ) in the applet causes the message “Welcome to the
world of Applet” to be displayed beginning at location 20,20.
Following block shows html code to be executed using browser –
<html>
<body> Java
Applets and GUI 157
Gzgewvkqp"Uvgru"hqt"Crrngv"Crrnkecvkqp"wukpi"dtqyugt"⁄
1. Write source code for applet application and save file with extension
‘.java’.
2. Compile source code with command ‘javac [Link]’. it
will create class file for source code.
3. Create HTML file and save with extension ‘.html’ in same directory
where class file for source code is stored.
4. Open html file using java enabled browser, which executes the applet.
kk0 Crrngv"Crrnkecvkqp"wukpi"CRRNGVXKGYGT
When an applet is to be executed using appletviewer, same applet
application code is written along with html code as discussed above. The code
for ‘WelcomeApplet’ is given in the block below.
import [Link].*; import [Link].*;
/*
<html>
<body>
<applet code="WelcomeApplet" width=200 height=60>
</applet>
</body>
</html>
*/
public class WelcomeApplet extends Applet
{
public void paint(Graphics g)
{
[Link]("Welcome to the world of Applet", 20, 20);
Java
158 Applets and GUI
“Only for Private Circulation”
} Java Programming
}
It can be seen that here both programs i.e. ‘[Link]’ and
‘[Link]’ are written in single file named as ‘[Link]’.
Execution steps are given as below –
Gzgewvkqp"Uvgru"hqt"Crrngv"Crrnkecvkqp"wukpi"crrngvxkgygt"⁄
1. Write source code for applet application and save file with extension
‘.java’.
2. Compile source code with command ‘javac [Link]’. It
will create class file for source code.
3. Execute the program using following command at command prompt
The command executes appletviewer application. It accepts source code
filename, and works on commented html code from source code.
Following image shows execution of an applet ‘WelcomeApplet’ through
appletviewer.
Crrngv"Nkhge{eng
We have already discussed every applet application is derived from class
‘Applet’ and it overrides methods defined in class ‘Applet’. These methods help
developer to define state specific behavior to applet application as well as to
control applet execution. In this section we are going to discuss about methods
which define different life cycle events of an applet. These methods help the
browser or applet viewer interfaces to the applet and controls its execution. Four
of these methods are —
• init( ) – Here ‘init’ stands for initialization. It is the method from which
applet execution starts. The method is executed when applet is executed
for the first time. Generally it is defined to initialize all data members as Java
it is executed only one time. Applets and GUI 159
The following code block represents skeleton for writing an applet with all
above defined methods –
// An Applet skeleton. import [Link].*; import [Link].*;
/*
Java <applet code="AppletSkel" width=300 height=100>
160 Applets and GUI
“Only for Private Circulation”
</applet> Java Programming
*/
public class AppletSkel extends Applet
{
// Called first. public void init( )
{
// initialization
}
/* Called second, after init(). Also calledwhenever the applet is restarted.*/
public voidstart()
{
// start or resume execution
}
// Called when the applet is stopped. public void stop()
{
// suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy()
{
// perform shutdown activities
}
// Called when an applet's window must be restored. public void
paint(Graphics g)
{
// redisplay contents of window
}
}
It is important to understand the order in which the various methods shown
in the skeleton are called.
When an applet begins, the AWT calls the following methods, in this
sequence:
• init( )
Java
• start( ) Applets and GUI 161
Eqpvtqnnkpi"Crrngv"Eqpvgpv
Applets have graphical user interface, and for the purpose as mentioned
above AWT classes are used to add graphics to an applet. Some of the methods
from AWT which help to design applet are as follows-
k0 ftcyUvtkpi*"+"<
It is a member of the Graphics class and so while calling it we need object
on class ‘Graphics’. Typically, it is called from within either update( ) or paint(
). It has the following general form –
voiddrawString(String message, intx, inty);
Here, messageis the string to be output beginning at x,y. In a Java window,
the upper-left corner is location 0,0. The drawString( ) method will not recognize
newline characters. If you want to start a line of text on another line, you must
do so manually, specifying the precise x,y location where you want the line to
begin.
For eg. the method draw string can be used as –
[Link](“Welcome to Applet”,20,20);
Here ‘g’ is an object on class ‘Grphics’. An applet window is referred as
‘Graphics’ object named ‘g’. The string passed as message is displayed at given
position by x and y.
kk0 ugvDcemitqwpf*"+."ugvHqtgitqwpf*"+<
setBackground( ) and setForeground( ) are used to design a colourful
[Link] color for an applet’s window can be set using
‘setBackground( )’, while to set the foreground color ‘setForeground( )’ is used.
These methods are defined by Component, and they have the following general
forms –
voidsetBackground(Color newColor);
void setForeground(Color newColor);
Both methods accepts color name as argument. ‘Color’ is the class defined
in Component hierarchy, which has defined different constants as variety of
colors. Different Color constants are shown here that can be used to specify
colors –
Java
162 Applets and GUI
“Only for Private Circulation”
[Link], [Link], [Link], [Link], [Link], Java Programming
[Link], [Link], [Link], [Link], [Link],
[Link], [Link]
For example, to set the background color to green and the text color to
yellow these methods can be used as –
setBackground([Link]);
setForeground([Link]);
Generally background and foreground colors are set in init( ) method for
an applet, from where applet execution starts. Runtime these colors can be
changed as per the requirement in any method. The default foreground color is
black. The default background color is light gray.
kkk0 igvDcemitqwpf*"+.igvHqtgitqwpf*"+"<
When we need to check background and fore ground colors for the current
applet, then these two methods can be used. These methods are defined by
Component. Syntax for these two methods is given as here –
Color getBackground( );
Color getForeground( );
Both these methods return ‘Color’ constant name.
kx0 ftcyNkpg*"+"<
The method from class Graphics draws line of 1 pixel thick joining two
pixels, start and end. With the method we need to pass start position and end
position, by specifying its x and y co-ordinates. Syntax for drawLine() method
is given as –
voiddrawLine(int x1, int y1, int x2, int y2);
For example –
[Link](10,10,30,40);
It uses current set color to draw line.
x0 ftcyTgev*"+."hknnTgev*"+"<
Both these functions defined in class ‘Graphics’ draws rectangle of given
size. First function ‘dawRect( )’ draws rectangle while ‘fillRect( )’ draws and
fills the rectangle by currently set color. Both methods accepts four arguments –
‘x’ coordinate, ‘y’ coordinate, width and height. According to width and height
arguments it calculates the ending position and draws the rectangle. Syntax for
both methods is given as –
voiddrawRect(int x1, int y1, int width, int height);
void fillRect(int x1, int y1, int width, int height); Java
Applets and GUI 163
xk0 ftcyRqn{iqp*"+."hknnRqn{iqp*"+
These polygon method draws closed polygon. Methods need all points to
be connected as polygon, which are passed as argument. Therefore a collection
of all points is passed as arrays, one for ‘x’ co-ordinates and other for ‘y’ co-
ordinates, as well as number of points to be plotted in polygon. The array is one
dimensional and is even in size, as two adjacent elements in array are co-ordinates
for one point in polygon. As arguments passed are coordinates for x and y and
hence size of both arrays should be same. Following syntax shows how we can
use methods ‘drawPolygon’ and ‘fillPolygon’.
voiddrawPolygon(int x[], int y[], intnumberOfPoints);
void fillPolygon(int x[], int y[], intnumberOfPoints);
For example –
intx[]={10,20,35,25};
inty[]={20,30,15,10};
[Link](x,y,4);
[Link](x,y, 4);
Ogvjqf"tgrckpv*+
When we want to add animation to applet then we need to use method
‘repaint()’. As discussed earlier method paint() is executed only once in sequence,
but when we want to add some moving objects to applet we can call repaint().
Following Program shows use of ‘repaint()’ method. The program uses concept
of ‘Thread’ which we discussed in chapter IV.
/*<applet code=BouncingBallSmooth width=500 height=500>
</applet> */
[Link].*; import [Link].*;
public class BouncingBallSmooth extends Applet implements Runnable
{
intx,y; intdx,dy; Thread t;
public void init()
{ x=40; y=40;
dx=30; dy=30;
Java
Applets and GUI 165
CYV"Eqpvtqnu
As stated in introduction package ‘awt’ provides wide variety of classes
helping to develop GUI for an application and these classes are arranged
hierarchically. The hierarchy of classes in ‘awt’ package is represented with the
help of following diagram shown in figure 6.1.
The classes in ‘awt’ acting as controls are derived from a super class
‘Component’. These controls are divided under three categories –
• Container classes – As the name suggests objects created on container
classes can store references to other control objects, and hence create
group of controls. The class ‘Container’ defines two sub classes –
‘Window’ and ‘Panel’. Sub classes from class ‘Window’, ‘Frame’ and
‘Dialogue’, are used for a desktop applications while the ‘Panel’ is used
for development of ‘Applets’. Responsibility of container objects is to
refer its controls collectively.
• Input controls – ‘TextField’, ‘TextArea’, ‘CheckBox’ etc. are input
controls which helps user to accept input from user. These are individual
controls and can be used as a part of a container.
• Output controls – ‘Label’ is a output control helps to give corresponding
messages for input.
• Processing Controls – the controls which are responsible for carrying
out process are the processing controls. ‘Button’ is a processing control.
• Navigation Controls – ‘Menu’ is acting as a navigation control which
helps to change control among different forms.
Java
166 Applets and GUI
“Only for Private Circulation”
Java Programming
Dwvvqp
It is an action based control defined in ‘awt’ package. Every button is
assigned with a ‘label’ which describes action in short taken by the ‘Button’,
hence labels for Buttons are action based words.
Following syntax explains how an object button can be defined –
Button <object name> = new Button(<label for Button>);
With the above syntax a Button object is created on class Button and is
assigned with the label passed as argument to constructor.
For example –
Button btnAdd = new Button(“Add”);
Above instruction defines a Button object which is referred by name
‘btnAdd’ and is assigned with label “Add”. The prefix used with every control
helps us to differentiate between different controls. For Button we use prefix as
‘btn’.
For finalizing its size and position method ‘setBounds()’ is executed.
‘setBounds’ accepts four arguments – first two arguments are its ‘x’ and ‘y’
positions, while last two arguments are width and height of the control. Following
instruction shows how method is called –
[Link](50,100,40,30);
For a Button we can add‘ActionListener’and to handle the action of ‘click’
add method ‘actionPerformed()’.
Ncdgn
It is an output control which helps to improve user interaction. When an
input control is expecting some input from user, it is explained with the help of
labels.
Following is the syntax for defining a label –
Label <object name> = new Label(<text for label>);
Label lblFNum = new Label(“Enter First Number : ”);
For example –
Here we have defined a Label with name ‘lblFNum’. While defining label
String is passed which will be displayed as it is. From the message given in
Java example you can understand that it is for explaining user of application about
168 Applets and GUI
“Only for Private Circulation”
the input value. Hence proper use of labels helps to improve user interface. Next Java Programming
is to ‘add’ label to container object and setting size of label using ‘setBounds()’
method. Like Button for label we can add ‘ActionListener’.
Vgzv"Hkgnf"
It is an input control. Generally when we need some input from user we can
use ‘TextField’. It can accept a single line text.
Syntax for defining object on ‘TextField’ is given below –
TextField<object name> = new TextField( );
For example –
TextFieldtxtFNum = new TextField( );
Here we have defined a new TextField object with name ‘txtFNum’. After
defining object add object to container and set size and position for the control.
For TextField we can add ‘KeyListener’ and override method ‘keyPressed’
or ‘keyTyped’ using which we can scan the input given by user.
Vgzv"Ctgc
It is same as TextField and have same properties and syntaxex. The only
difference between TextField and TextArea is it can accept multiple lines as
input. Generally TextArea is used while accepting address or feedback where
user need to enter multiple lines.
Ejgemdqz
It is again an input control used to accept value as true or false by checking
or non checking the option. It stores value of type Boolean. When we want to
accept an input from user which has only two possible values ‘true’ or ‘false’
then we can use checkbox. For example marital status, gender etc. Following
syntax shows how a checkbox object can be declared –
Checkbox <object name> = new Checkbox (<label> [, <default value>]);
For example –
Checkbox chkUnmarried= new Checkbox (“Unmarried”,true);
Checkbox chkMarried= new Checkbox (“Married”);
By default checkbox value is unchecked i.e. false. If while defining you
need to define as checked then we can set its value to true, but it is optional. In
the above example we have defined two checkboxes ‘chkUnmarried’ and
‘chkMarried’. We have assigned default value for ‘chkUnmarried’ as true while
for other as false.
With checkbox we can add ‘ItemListener’ for which we need to override
method ‘itemStateChanged’ which is executed when user clicks on checkbox and
changes its status. Java
Applets and GUI 169
Ogpw
Menu in java consists of three components –
• Menu bar
• Menu
• Menu item
Menu bar is a component which consists of different menus while a menu
consists of menu item. ‘MenuBar’ is the class which allows user to define object
for menu bar. For defining menu class ‘Menu’ is used, while for defining menu
items class ‘MenuItem’ is used. These different objects can be linked with each
other by adding object of MenuItem to Menu and adding Menu objects to
MenuBar and adding MenuBar to form.
Following syntaxes shows how objects on these classes can be defined –
MenuBar<object Name>=new MenuBar( );
Menu <object Name>=new Menu(<Label for Menu>);
MenuItem<object Name>=new MenuItem(<Label for Menu>);
MenuBarmainMenu=new MenuBar( ); Menu menu1=new
Menu(“Menu1”); Menu menu2=new Menu(“Menu2”);
MenuItem menuItem11=new MenuItem(“Menu Item1 in Menu1”);
MenuItem menuItem21=new MenuItem(“Menu Item1 in Menu2”);
Following example explains how objects can be declared on these
components –
Here in the above code we have defined a menu bar with name ‘mainMenu’.
In ‘mainMenu’ we have defined ‘menu1’ and ‘menu2’. Under each menu we
have defined one menu item, ‘menuItem11’ in ‘menu1’ and ‘menuItem21’ in
‘menu2’. Here we need to link these items with each other as follows –
Frame f=new Frame(); [Link](mainMenu);
[Link](menu1);
[Link](menu2);
Java
[Link](menuItem11); [Link](menuItem21);
170 Applets and GUI
“Only for Private Circulation”
Ucorng"Rtqitco"wukpi"flcyv‚" Java Programming
Output for the above program is given as -
/*Finding Largest out of 3 using awt*/ import [Link].*;
[Link].*;
public class Max3num extends Frame implements
ActionListener,TextListener
{
Label l1,l2,l3,l4; TextField t1,t2,t3,t4; Button submit,reset;
int num1,num2,num3,max; String num1str,num2str,num3str;
/*Constructor for class Max3num*/ public Max3num()
{
super("Maximum Of Three Numbers"); setLayout(new FlowLayout());
l1 = new Label("Enter FirstNumber"); add(l1);
t1 = newTextField(10); add(t1);
l2 = new Label("Enter SecondNumber"); add(l2);
t2 = newTextField(10); add(t2);
l3 = new Label("Enter ThirdNumber"); add(l3);
t3 = newTextField(10); add(t3);
submit = new Button("SUBMIT"); add(submit);
reset = new Button("RESET"); add(reset);
l4 = new Label("Maximum of 3 numbers are"); add(l4);
t4 = new TextField(10); add(t4);
[Link](this); [Link](this); [Link](this);
[Link](this); [Link](this);
}
public void textValueChanged(TextEventte)
{
if ([Link]() == t1)
{
num1str = [Link]();
num1 = [Link](num1str); [Link]("Maximum of "+num1);
}
else if ([Link]() == t2) Java
Applets and GUI 171
*****
Java
Applets and GUI 173
Tghgtgpegu"⁄
Dqqmu"⁄
1. ‘The Complete Reference – Java 2’, Fifth Edition, Herbert Schildt
2. ‘Core Java Volume 1- Fundamentals’, Eighth Edition, Cay S.
Horstmann, Gray Cornell Websites –
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. ss[Link]
7. [Link]
8. [Link]
*****
Java
174 Applets and GUI
“Only for Private Circulation”