You are on page 1of 318

OOP Definition

Concepts of Classes and objects


OOPs Features


2
- Encapsulation / Data Hiding
-Abstraction
-Inheritance
-Polymorphism
-Dynamic Binding
-Message Passing
Contents of this session
+ OOP is a programming methodology that helps to organize
a complex programs through the use of inheritance,
encapsulation and polymorphism

+ To access the class, we need an instance which can create
an logical interface in between class & user (through main
function). Such instance is termed as Object. That why this
new paradigm is termed as Object Oriented Programming
Paradigm
3
+ OOP increasing the flexibility in coding without disturbing
the other part of the code

+ OOP increasing the software development speed by reusing &
enhancing the existing code
An object is like a
black box.
The internal details
are hidden.
Identifying objects and assigning
responsibilities to these objects.

Objects communicate to other
objects by sending messages.

Messages are received by the
methods of an object
5
Everything in the world is an object.
For example-








Real world objects share two characteristics: They all have
state(attributes) and behavior (action). Dogs have state(name,
color etc) and behavior (barking, wagging tails etc).
Tangible Things as a car, printer, ...
Roles as employee, boss, ...
Incidents as flight, overflow, ...
Specifications as colour, shape,

7

An object represents an individual, identifiable item, unit, or
entity, either real or abstract, with a well-defined role in the
problem domain.
Or
An "object" is anything to which a concept applies.
Etc.
8
Defining Class
A CLASS is a template (specification, blueprint)
for a collection of objects that share a common
set of attributes and operations.
HealthClubMember
Class



Objects
attributes
operations
10
Class & Instance

Class defines a new data types
Once defined, this new type can be used to create objects of
that type
Class is a template for an object and, an object is an instance
of a class
The data or variables, defined within a class are called
instance variables
The code is contained within methods
Collectively, the methods and variables defined within a class
are called members of a class
11
Furniture
Chair
Table
Book self
Common Behavior:
Keeping something


RealLife Object: State-Variable
Behavior-method
Example:-
Modularity - large software projects can be split up in
smaller pieces.

Reusability - Programs can be assembled from pre-
written software components.

Extensibility - New software components can be written
or developed from existing ones.
13
Features of 100% OOP Languages:

1) Encapsulation / DataHiding
2) Abstraction
3) Inheritance
4) Polymorphism
5) Dynamic Binding
6) Message Passing
ENCAPSULATION / DATAHIDINGABSTRACTION


ENCAPSULATION Binding or Wrapping of the data and
methods into a single unit is called Encapsulation.
Encapsulation is used to hide data or protect
data from outside access. So this concept is also called data-
hiding.
ABSTRACTION Abstraction refers to the act of representing
essential features without including the background details
and explanation.
explanation the capsule cures the patient.. But the patient
dont know what is capsulated inside the capsule..
CAPSULE
MEDICINE INSIDE THE CAP
16
Encapsulation ensures that data within an object is
protected; it can be accessed only by its methods
ENCAPSULATION
INHERITANCE
Inheritance is a process, through which we can create a new
class from an existing class.







In Java extends key word is used
Parent , Super, Base Class
Child , Sub , Derived Class
18
Vehicle
2 Wheeler 3 Wheeler 4 Wheeler
Kinetic Scooter
is-a kind of hierarchy
Inheritance hierarchy
INHERITANCE

Inheritance is the process by which new classes
called derived classes are created from existing classes
called base classes. The derived classes have all the features of
the base class and the programmer can choose to add new
features specific to the newly created derived class.



A car is a vehicle
A teacher is a person
A dog is an animal
POLYMORPHISM
=PLOY MORPH(MANY FORMS)
Anything which has more than one form depending on the
situation.

Polymorphism means having many forms. It allows
different objects to respond to the same message in
different ways, the response specific to the type of the
object.

In Java, polymorphism refers to the fact that you can have
multiple methods with the same name in the same class




POLYMORPHISM
21
Move ( )
Move ( )
Move ( )
Move ( )
CORE JAVA-OOP CONCEPTS
Two types of Polymorphism
1. Compile-time/Static Polymorphism early binding or static
binding.. ex: Method Overloading
Method Overloading is a process where the same function
name is used for more than one type/Functions can be
overloaded based on the function signature.
Method Signature are:
The no of Parameters
Type of Parameters
Sequence of Parameters

**Functions can not be overloaded based on return type.


2. Run-time/Dynamic Polymorphism late binding or dynamic
binding.. ex: Method Overriding
- Replacing an inherited method with another having the same
signature
- Create a method in a subclass having the same signature as a
method in a superclass
- That is, create a method in a subclass having the same name
and the same number and types of parameters
Restrictions:
The return type must be the same




Message Passing
The most important aspect of an object is its behaviour (the
things it can do). A behaviour is initiated by sending a
message to the object (usually by calling a method).
24


For example: Message Passing

In a banking system there is two object one is customer &
other is account number. when any customer object sent a
message to the account object requesting for the balance, the
account object replies with the figure..


+Code reusability

+Security

+Software complexity decreases

+ Easy Debugging



Encapsulation
code quality, ease of maintenance
Inheritance
efficiency, extensibility.
Polymorphism
power!

State the history of Java

Java Applications

Describe features of Java

Summary
28
JAVE SE(Java Platform, Standard Edition)-
FORMERLY J2SE

Java for the desktop / workstation

JAVA EE(ENTERPRISE EDITION)-FORMERLY
J2EE

Java for the server programming

JAVA ME(MOBILE EDITION)-FORMERLY
J2ME(MICRO EDITION)

Java platform designed
for embedded system


29
Program
These are the set of instructions directing the computer to do
some action

programming languages
Languages for specifying sequences of directions to a
computer

Software:
It is the logical part of computer system, which is made up by
several programs. In short, It is set of Programs.

30
Programs are written using programming languages.

Java - The new programming language developed by James
Gosling and others at Sun Microsystems in 1991.

Originally called Oak by James Gosling, one of the inventors
of the Java Language.

Java is really C++ -- ++

31
C++

C Java

Java Authors: James Gosling , Arthur Van , and others

Originally created for consumer electronics (TV, VCR, Freeze,
Washing Machine, Mobile Phone)

Many of Javas object-oriented features were influenced by
C++

Oak was renamed to Java in May 1995.

32

Its the current hot language

Its almost entirely object-oriented

It has a vast library of predefined objects and operations

Its more platform independent
this makes it great for Web programming

Its more secure
33
Java is a general purpose ,Object-oriented
programming language. We can develop three types
of applications in Java

Stand alone Applications

GUI Applications

Applet Applications

Java Applications
Java
Source
Code
Java Compiler
Java Enabled
Web browser
Java Interpreter
Output
Output
Standalone and GUI
applications
Applets
Java Applications cont
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
36
Java is partially modeled on C++,
but greatly simplified and improved.

No pointers

Automatic garbage collection


Does not use header files and
preprocessors (like #include or #define)

Rich pre-defined class library


Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
37
Focus on the data (objects) and
methods manipulating the data

Object-oriented programming
provides great flexibility, modularity,
clarity, and reusability through
encapsulation, inheritance, and
polymorphism.


Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
38
Works on a variety of platforms

Provides support for:

Networking: via Socket Programming

Internet: The widely used protocols
like HTTP and FTP are developed in
java

Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
39
You need an interpreter to run Java
programs. The programs are compiled
into the Java Virtual Machine code
called bytecode. The bytecode is
machine-independent and can run on
any machine that has a Java interpreter,
which is part of the Java Virtual
Machine (JVM).
JAVA COMPILER
JAVA BYTE CODE
JAVA INTERPRETER
Windows 95
Macintosh Solaris Windows NT
(translator)
(same for all platforms)
(one for each different system)
40
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust(Reliable)
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
41
Java compilers can detect many
problems that would first show up
at execution time in other
languages.

Memory protection and
management
(using garbage collection)

Java has a runtime exception-
handling feature to provide
programming support for
robustness.
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
42
The Java language has built-in
capabilities to ensure that violations
of security do not occur.

Access restrictions are forced
(private, public)

The absence of pointers in java
ensures that programs cannot gain
access to memory location without
proper authorization.


Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
43
Write once, run anywhere

With a Java Virtual Machine (JVM),
you can write one program that will
run on any platform.
A.class A.java
Java
Compiler
B.class
Loader
Verifier
Linker
Bytecode Interpreter
Java Virtual Machine
Compile source code
Java Virtual Machine Architecture
44
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
45
Because Java is architecture
neutral, Java programs are
portable. They can be run on any
platform without being recompiled.
Like

MacOS
Windows XP/Vista/2007
Solaris
Linux
Unix etc

Byte code

The sizes of the primitive data
types are machine independent.

46
Source
Code
Byte
Code
.Java file
Windows
Mac
UNIX
Compile
.class file
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
47
Javas performance Because Java is
architecture neutral, Java programs are
portable. They can be run on any
platform without being recompiled.

just-in-time(Midway between compiling
and interpreting) compiling & native
code

JVM running
Applet or
Application
JIT
COMPILER
.class file
machine code
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
48
Multithread programming is
smoothly integrated in Java,
whereas in other languages you
have to call procedures specific to
the operating system to enable
multithreading.

multiple concurrent threads of
executions can run simultaneously

Multi tasking.

Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
49
Java was designed to adapt to an
evolving environment. New code
can be loaded on the fly without
recompilation. There is no need for
developers to create, and for users
to install, major new software
versions. New features can be
incorporated transparently as
needed.

Java provides dynamic linking of
the binary code at runtime.

What did make Java so successful?

Portability

Reliability

Safety

Simplicity
50


Java has emerged as a general purpose OO language.


It supports both stand alone and Internet Applications.


Makes the Web Interactive and medium for application delivery.
51
+ The major differences between C++ & JAVA

+ Getting Started With Java Programming

Create, Compile and Running a Java Program

52


+ Both Java and C++ are most popular object-oriented
programming languages

+ C++ was created at AT&T Bell Labs in 1979

+ Java was born in Sun Microsystems in 1990

53


C Java
C+
+
Java Vs. C++
No Preprocessor
No Global Variables
No Goto statements
No Pointers
No Unsafe Structures
No Multiple Inheritance
No Operator Overloading
No Fragile Data Types
54
Java
Powerful language
Programming
Clarity - Keep it Simple
Portability - Java portable, but it is an elusive goal
Performance
Interpreted programs run slower than compiled ones
Compiling has delayed execution, interpreting executes
immediately
Can compile Java programs into machine code
Runs faster, comparable to C / C++
55
The secret behind the security and portability of Java is that
the output of a Java compiler is not executable code. Rather, it
is byte code

Byte code is a highly optimized set of instructions designed to
be executed by the Java run-time system, which is called the
Java Virtual Machine (JVM)

JVM is an interpreter of byte code
56
Java Vs. C++
Bytecode
JVM
OS kernel
Binary code
OS kernel
JAVA
source code
C++
source code
javac
compiler
C++ compiler gcc, turboc,turbo c++
Java
interpreter
Java compiler

Both compiled and interpreted Compiled
Java is Both compiled and interpreted
Java Vs. C++
57
The .class files generated by the compiler are not executable
binaries. Instead, they contain byte-codes to be executed by
the Java Virtual Machine.
write once, run anywhere language.
Java Vs. C++
58
+Everything MUST be in a class.
There are no global functions or global data. If you want
the equivalent of globals, make static methods and
static data within a class.
There are no structs or enumerations or unions, only
classes.




+Java has both kinds of comments like C++ does.




59
Java Vs. C++
+Java has no preprocessor.
If you want to use classes in another library, you say import
and the name of the library.
There are no preprocessor-like macros.



60
+ All the primitive types in Java have specified sizes that are
machine independent for portability.
Java Vs. C++
+ There is a garbage collection in JAVA
Garbage collection means memory leaks are much harder to
cause in Java, but not impossible. (If you make native
method calls that allocate storage, these are typically not
tracked by the garbage collector.)



61
+ There are no destructors in Java.
- There's no need because of garbage collection.
62
C++ JAVA
C++ supports classes,
structures or
unions.
Java supports only classes.
In C++ class definition, class
is closed by semicolon after
the curly brace.
In Java class definition is very
similar
as C++, but presence of
semicolon is
not required.
Uses scope resolution
operator (::).
Not using scope resolution
operator (::).
Some other differences
Feature C++ Objective

Ada Java
Encapsulation
Yes Yes Yes Yes
Inheritance
Yes Yes No Yes
Multiple Inherit.
Yes Yes No No
Polymorphism
Yes Yes Yes Yes
Binding (Early or Late)
Both Both Early Late
Concurrency
Poor Poor Difficult Yes
Garbage Collection
No Yes No Yes
Genericity
Yes No Yes Limited
Class Libraries
Yes Yes Limited Yes


63


class HelloWorld
{
public static void main(String args[])
{
System.out.println(Hello World);
}
}

64


class HelloWorld name of the class
{
public static void main(String args[])
{
System.out.println(Hello World);
}
}

65
class HelloWorld
{
public static void main(String args[])
{
System.out.println(Hello World);
}
}
Public is a access specifier that declares the method ad
unprotected and therefore making it accessible to all other classes.

Static static is a keyowrd ,which declares this method as one that
belongs to the entire class and not a part of any objects of the class.

Void does not return anything.
66


class HelloWorld
{
public static void main(String args[]) Defining
main method
{
System.out.println(Hello World);
}
}
arr[]takes the values of command line arguments..
Suppose we are giving a b c
darr[0]=a,arr[1]=b,arr[2]=c,arr[3]=d

67
String array as argument
class HelloWorld
{
public static void main(String args[])
{
System.out.println ( Hello World);
}
}

System System is a class under java.lang
package.java.lang.Objectjava.lang.System

outout is the object of PrintStream class.

println()is the method that prints in a new line.

68
69
Text Editor Compiler Interpreter
Programmer
Source Code
.java file
Byte Code
.class
file
Hardware and
Operating System
java
c
.exe
file
70
71
Java is CASE SENSITIVE!!

Whitespace is ignored by compiler

Whitespace makes things easier to readhence it affects your
grade

File name has to be the same as class name in file.

Need to import necessary class definitions

72
Data types
Identifier
Variable
Comments
Reserved Words
Operators
73
byte, short, int, and long
for integer values of various sizes
float and double
for real (rational) values of differing accuracy
boolean
for logical (true/false) values
char
for individual characters
PRIMITIVE SIZE IN BITS Default Values
long 8 bytes 0L
int 4 bytes 0
short 2 bytes 0
byte 1 bytes 0
float 8 bytes 0.0f
double 4 bytes 0.0d
char 2 bytes
(unicode)
\u0000
bool (boolean in
Java)
1 bytes false
Integers
4, 19, -5, 0, 1000
Doubles
3.14, 0.0, -16.123
Strings
Hi Mom Enter the number :
Character
'A' 'X' '9' '$' '\n'
Boolean
true, false

An identifier is a sequence of characters that consist of letters,
digits, underscores (_), and dollar signs ($).
Identifier = the technical term for a name in a programming
language

Identifier naming rules:
The first character must not be a digit.
May begin with a letter or the underline character _
If these rules are broken, your program won't compile.

Must not be a Java keyword
Names must be descriptive.

Identifiers
Identifier examples
class name identifier: Hello
method name identifier: main
variable name identifier: height

Constants
All caps with _ between words

A variables can be considered as a name given to the
location in memory where values are stored.

How does the computer know which type of data a
particular variable can hold?
Before a variable is used, its type must be declared in a
declaration statement.

Declaration statement syntax:
<type> <list of variables separated by commas>;
12
Syntax:
type variable_name;
or
type variable_name = expression;

Note
type must be known to the compiler
variable_name must be a valid identifier
expression is evaluated and assigned to variable_name
location
In the first form, a default value is given (0, false, or null,
depending on type)
There are two types of comments used in Java. These are:

In Java, comments are preceded by two slashes (//) in a line

Or enclosed between /* and */ in one or multiple lines.

When the compiler sees //, it ignores all text after // in the
same line.

When it sees /*, it scans for the next */ and ignores any text
between /* and */.
Reserved words or keywords are words that have a specific
meaning to the compiler and cannot be used for other purposes
in the program.


For example, when the compiler sees the word class, it
understands that the word after class is the name for the class.


Other reserved words are like public, static, and void. Their use
will be introduced later in the book.
83
Java Keywords
abstract boolean break byte case
catch char class continue default
do double else extends false
final finally float for if
implements import instanceof int interface
long native new null package
private protected public return short
static super switch synchronized this
throw throws transient true try
void volatile while
Keywords that are reserved but not used by Java
const goto

Keywords are words reserved for Java and cannot be used as identifiers or
variable names
Java Keywords
Types of operators

Simple Assignment Operator
= (Simple assignment operator)

Arithmetic Operators
+ (Additive operator (also used for String concatenation))
- (Subtraction operator)
* (Multiplication operator)
/ (Division operator)
% (Remainder operator)

85
Unary Operators
+ (Unary plus operator; indicates positive value)
- (Unary minus operator; negates an expression)
++ (Increment operator; increments a value by 1)
-- (Decrement operator; decrements a value by 1)
! (Logical compliment operator; inverts the value of a
boolean)

Equality and Relational Operators



86
== (Equal to)

>= (Greater than or equal to)
!= (Not equal to) < (Less than)
> (Greater than) <= (Less than or equal to)
Operators cont
Conditional Operators
&& (Conditional-AND)
|| (Conditional-OR)
?: (Ternary (shorthand for if-then-else statement))

Type Comparison Operator
instanceof (Compares an object to a specified type)

87

Bitwise and Bit Shift Operators

~ (Unary bitwise complement)
<< (Signed left shift)
>> (Signed right shift)
>>> (Unsigned right shift)
& (Bitwise AND)
^ (Bitwise exclusive OR)

Operand should be integer type

88
Bitwise AND
1001
2
& 0011
2
= 0001
2

Bit OR
1001
2
| 0011
2
= 1011
2
Exclusive OR
1001
2
^ 0011
2
= 1010
2

1s Complement
~ 00001010
2
= 11110101
2

Operators cont

+ Control statement

+ Array
90
if statement

switch statement

conditional operator
Writing if Statements
if statement:
Interrogates logical expression enclosed in parentheses
boolean expressions can use just one word
example:
boolean isFound=true;
if (isFound)
System.out.println(The object is found.);
Determines whether it is true or false
Uses logical operators to compare values
Writing if Statements
You dont need the brackets for only one statement.
if statements can contain compound expressions
Two expressions joined using logical operators
OR ||
AND &&
Nested if statement
if statement written inside another if statement
the else statement always corresponds with the closest if
statement
Using the Conditional Operator
Conditional operator (?)
Provides a shortcut to writing an if-else statement
Structure:
variable = expression ? value1:value2;
example
int smallerNumber = (a < b) ? a : b;

Writing switch Statements
Acts like a multiple-way if statement
Transfers control to one of several statements or blocks
depending on the value of a variable
Used when there are more than two values to evaluate
Restrictions:
Each case evaluates a single variable for equality only
Variable being evaluated must be: char, byte, short, or int
char eventType;

switch (eventType)
{
case A:
eventCoordinator = Dustin;
break;
case B:
eventCoordinator = Heather;
break;
case C:
eventCoordinator = Will;
break;
default:
eventCoordinator = Invalid Entry;
}
Loops
Provides for repeated execution of one or more statements
until a terminating condition is reached
Three basic types:
while
do
for
What is the difference between the while and do loops?
Following figure shows a while loop that prints the integers
through 10
Post-test loop
Tests terminating condition at the end of the loop
Forces execution of statements in the loop body at least
once
Example:
do
{
System.out.println(count = + count);
count++;
}
while (count <= 10);
Pre-test loop
Tests terminating condition at the beginning of the loop
Includes counter initialization and incrementing code in the
statement itself
Example:
for (int count=1; count<=10; count++)
{
System.out.println(count = + count);
}
An array is a group of contiguous or related data items that
share a common name.
Used when programs have to handle large amount of data
Each value is stored at a specific position
Position is called a index or superscript. Base index = 0
The ability to use a single name to represent a collection of
items and refer to an item by specifying the item number
enables us to develop concise and efficient programs.
For example, a loop with index as the control variable can be
used to read the entire array, perform calculations, and print
out the results.
Creating an array is a 2 step process
It must be declared (declaration does not specify size)





It must be created (ie. memory must be allocated for the
array)

Creating Arrays
type[] arrayName;

declaration syntax:
note the location of the []
int[] grades; // declaration

grades = new int[5]; // Create array.
// specify size
// assign new array to
// array variable

int[] grades = new int[5];

When an array is created, all of its elements are automatically
initialized
0 for integral types
0.0 for floating point types
false for boolean types
null for object types
Creating Arrays
0
0
0
0
0
4
3
2
1
0
array indices
Note: maximum array index is length -1
grades
Because array elements are initialized to 0, the array should be
initialized with usable values before the array is used.
This can be done with a loop
Arrays have a length attribute which can be used for bounds
checking
Elements are accessed using an index and []

Initializing and Using Arrays
int[] sequence = new int[5];

for (int i=0; i< sequence.length; i++)
{
sequence[i] = i * 25;
}
array length: ensures loop
won't go past end of the array
Array element being accessed. In this
case, it is being assigned a value.
Another way of initializing lists is by using initializer lists.
The array is automatically created
The array size is computed from the number of items in the
list.

Using initialize lists
int[] grades = {100, 96, 78, 86, 93};
type[] arrayName = {initializer_list};

String[] colours = { "Red", "Orange",
"Yellow", "Green",
"Blue", "Indigo",
"Violet"};
Two dimensional arrays
allows us to store data
that are recorded in table.
For example:

Table contains 12 items,
we can think of this as a
matrix consisting of 4
rows and 3 columns.

Item1 Item2 Item3
Salesgirl #1 10 15 30
Salesgirl #2 14 30 33
Salesgirl #3 200 32 1
Salesgirl #4 10 200 4
109
Sold
Person
Declaration:
int myArray [][];
Creation:
myArray = new int[4][3]; // OR
int myArray [][] = new int[4][3];
Initialisation:
Single Value;
myArray[0][0] = 10;
Multiple values:
int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}};
int tableA[][] = {{10, 15, 30}, {14, 30, 33}};

11
0
Arrays can be used to store objects

Circle[] circleArray;
circleArray = new Circle[25];


The above statement creates an array that can store
references to 25 Circle objects.

Circle objects are not created.








11
1
Create the Circle objects and stores them in the array.
//declare an array for Circle
Circle circleArray[] = new Circle[25];
int r = 0;
// create circle objects and store in array
for (r=0; r <25; r++)
circleArray[r] = new Circle(r);
11
2
Classes and objects

Constructors

this keyword

Garbage Collection

finalize() Method



11
3
Defining Class
A CLASS is a template (specification, blueprint)
for a collection of objects that share a common
set of attributes and operations.
HealthClubMember
Class



Objects
attributes
operations
11
5
Class & Instance

Class defines a new data types
Once defined, this new type can be used to create objects of
that type
Class is a template for an object and, an object is an instance
of a class
The data or variables, defined within a class are called
instance variables
The code is contained within methods
Collectively, the methods and variables defined within a class
are called members of a class
116
class classname{
access modifiers:
type instance-variable1
//
type instance-variable N
access modifiers:
type methodname1(parameter-list){
//body of the method
}
//
type methodname N(parameter-list){
//body of the method
}
}
117
private
same class only

public
everywhere

protected
same class, same package, any subclass

(default)
same class, same package
General form of a class does not specify a main( ) method


Class declaration and implementation of the methods are
stored in the same place and not defined separately (Different
from the C++)


Sometimes .java files become very large

119
class Box
{
double width;
double height;
double depth;
}

This code does not cause any objects of type Box to come
into existence

To actually create a Box object, you will use a statement like:
Box mybox = new Box(); // create a Box object called mybox
120
Here is a complete program that uses the Box class
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;

// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;

System.out.println("Volume is " + vol);
}
}
121

To obtain objects of a class, we need
First declare a variable of the class type
Second, acquire an actual, physical copy of the object and
assign it to that variable (by new operator)

In Java, all class objects must be dynamically allocated

Object references appear to be similar to pointers, but you
can not manipulate references as you actual pointers

122
123
Statement Effect

Box mybox;

mybox


mybox=new Box( );

mybox


Box object
null
Width

Height
Depth

mybox=new Box();

The class name followed by parentheses specifies the
constructor for the class
If a class dont explicitly define its own constructor, the Java
automatically supply a default constructor
We dont need to use new for integers or characters.
Because javas simple types are not implemented as objects
It is possible that new will not be able to allocate memory
for an object because of insufficient memory. In that case, a
run-time exception will occur
124
Box b1=mew Box();
Box b2=b1;
b1 and b2 will both refer to the same object


b1

b2



Box object
If b1 is assigned null (b1=null;), the b2 still points to the
original object

125
Width
Height

Depth

class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// display volume of first box
mybox1.volume();
}
}
126
class Box {
double width;
double height;
double depth;
double volume( ) { // compute and return volume
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[ ]) {
Box mybox1 = new Box();
double vol;
mybox1.width = 10; // assign values to mybox1's instance variables
mybox1.height = 20;
mybox1.depth = 15;
vol = mybox1.volume( ); // get volume of first box
System.out.println("Volume is " + vol);
}
}
127

There are two problems in the previous code
Its is clumsy and error prone (you may forget to set
dimension)
Instance variables should be accessed only through
methods defined by their class

void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
mybox1.setDim(10, 20, 15);
128

A constructor is automatically called immediately after the
object is created, before the new operator completes

Its has no return types, not even void

Constructors have the same name as the classname

When we write Box mybox1=new Box( ); actually the
constructor for the class is being called

As you know, Java creates a default constructor for the class,
which initializes all instance variables to zero
129
Constructor

Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}

When you write Box mybox1=new Box( ); the values of height,
width and depth are automatically assigned
130

Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}


Box mybox1 = new Box(10, 20, 15);
131
Sometimes a method will need to refer to the object that
invoked it. To allow this, Java defines the this keyword


this can be used inside any method to refer to the current
object. this always refers to the object on which the method
was invoked

132

- This is always a reference to the object on which the method
was invoked.
// A redundant use of this.
Box( double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}

- The this keyword is used to resolve name-space collisions
when instance variables are hidden by local variables.

Box( double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}



133

Sometimes an object will need to perform some action when
it is destroyed (i.e. release some non-java resources such as
file handle or windows character font)
finalize( ) method allows us to define specific actions that
will occurs when an object is just about to be reclaimed by
the garbage collector
protected void finalize( )
{
//finalization code here
}
You cannot know when- or even if- finalize( ) will be
executed. Therefore, you must not rely on it for normal
program execution

134


Method Overloading


Constructor Overloading


Static variable and method




13
5

Methods are distinguished by their signature:
name
number of arguments
type of arguments
position of arguments
That means, a class can also have multiple usual methods
with the same name.

Not to confuse with method overriding (coming up), method
overloading:
13
6

class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
137




class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}


This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
138
Overloading Method example cont

Constructor is a special method that gets invoked
automatically at the time of object creation.

Constructor is normally used for initializing objects with default
values unless different values are supplied.

Constructor has the same name as the class name.

Constructor cannot return values.

A class can have more than one constructor as long as they have
different signature (i.e., different input arguments syntax).
13
9

Sometimes want to initialize in a number of different ways,
depending on circumstance.


This can be supported by having multiple constructors
having different input arguments.
14
0
14
1


public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centreX, double cenreY, double
radius) {
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }

//Methods to return circumference and area
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}






14
2
public class TestCircles {

public static void main(String args[]){
Circle circleA = new Circle( 10.0, 12.0, 20.0);
Circle circleB = new Circle(10.0);
Circle circleC = new Circle();
}
}
circleA = new Circle(10, 12, 20) circleB = new Circle(10)
Centre = (0,0)
Radius=10
circleC = new Circle()
Centre = (0,0)
Radius = 1
Centre = (10,12)
Radius = 20
14
3
Method Overloading
Using one object we
can call all the
methods having same
name
Example:
A a=new A();
a.add(12,14);
a.add(11.5,16.8);
a.add(10,15,20);
Constructor Overloading
We need different objects
to call each constructors


Example:
Area a=new Area();
Area a1=new Area(4);
Area a2=new Area(4.0);





Java supports definition of global methods and variables that
can be accessed without creating objects of a class. Such
members are called Static members.

Define a variable by marking with the static methods.

This feature is useful when we want to create a variable
common to all instances of a class.

One of the most common example is to have a variable that
could keep a count of how many objects of a class have been
created.

Note: Java creates only one copy for a static variable which
can be used even if the class is never instantiated.

14
4
Using static variables:






14
5
public class Circle {
// class variable, one for the Circle class, how many
circles
private static int numCircles = 0;
private double x,y,r;

// Constructors...
Circle (double x, double y, double r){
this.x = x;
this.y = y;
this.r = r;
numCircles++;
}
}

Using static variables:






14
6
public class CountCircles {

public static void main(String args[]){
Circle circleA = new Circle( 10, 12, 20); // numCircles = 1
Circle circleB = new Circle( 5, 3, 10); // numCircles = 2
}
}
circleA = new Circle(10, 12, 20)
circleB = new Circle(5, 3, 10)
numCircles


Instance variables : One copy per object. Every object has
its own instance variable.
E.g. x, y, r (centre and radius in the circle)


Static variables : One copy per class.
E.g. numCircles (total number of circle objects created)




14
7
A class can have methods that are defined as static (e.g.,
main method).

Static methods can be accessed without using objects. Also,
there is NO need to create objects.

They are prefixed with keyword static

Static methods are generally used to group related library
functions that dont depend on data members of its class. For
example, Math library functions.
14
8
public class HowToAccessStaticMethod
{
int i;
static int j;
public static void staticMethod(){
System.out.println("you can access a static method this way");
}
public void nonStaticMethod(){
i=100;
j=1000;
System.out.println("Don't try to access a non static method");
}
public static void main(String[] args) {
//i=100;
j=1000;
//nonStaticMethod();
staticMethod();
}}

14
9
They can only call other static methods.

They can only access static data.

They cannot refer to this or super (more later) in anyway.
15
0


Inheritance

Method overriding

Difference between Method overloading & Method overriding




15
1
Inheritance is a process, through which we can create a new
class from an existing class.








In Java extends key word is used
Parent , Super, Base Class
Child , Sub , Derived Class
A class that is inherited is called superclass
The class that inherits is called subclass
A subclass is a specialized version of a superclass
extends keyword is used to inherit superclass
Java does not support multiple superclasses into single
subclass (This differs from C++)
A subclass can be a superclass of another subclass
So class can be a superclass of itself
153
1.Single Inheritance:
class A
{
//code
}
class B extends A
{
//code
}

A
B



2.Multilevel Inheritance:

class A
{
//code
}
class B extends A
{
//code
}
class C extends B
{
//code
}

A
B
C

3.Multiple Inheritance:


A
B C D
Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical
3.Multiple Inheritance: Not supported by Java.


A
B
C D
Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical




3.Multiple Inheritance: Not supported by
Java.
Diamond ProblemBut supported by
C++ To Overcome this problem we
have the concept of Interface..
A
B
C
D
Inheritance: Inheritance is a process, through which we can create a new class from an
existing class.
4.Hierarchical Inheritance:
class A
{
//code
}
class B extends A
{
//code
}
class C extends A
{
//code
}
class D extends A
{
//code
}
A
B C D

If a superclass keeps its data members private, then there
would be no way for subclass to directly access or initialize
its parents instance variables

The solution is the use of keyword super

Whenever a subclass needs to refer to its immediate
superclass, it can do so by use of the keyword super

Super has two general forms,
For accessing constructors
For accessing hidden member of superclass
160
super (parameter-list)
super( ) must always be the first statement executed inside a
subclass constructor

// BoxWeight now uses super to initialize its Box attributes.
class BoxWeight extends Box {
double weight; // weight of box

// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}
161
Here super acts as somewhat like this
super.member
Mostly applicable when member names of a subclass hide
members by the same name in the superclass

// Using super to overcome name hiding.
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A

B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
162

Method Overriding is a process through which a base class
method overridden by a derived class method

For method Overriding Method name and signature should
be same.

When a overridden method is called from within a subclass, it
will always refer to the version of that method defined by the
subclass

Like virtual functions in C++
163
164
Example
class B extends A {
int k;

B(int a, int b, int c) {
super(a, b);
k = c;
}

void show() {
super.show( ); // this calls A's show()
System.out.println("k: " + k);
}
}
165


Method overriding occurs only when the names and the type
signatures of the two methods are identical


If they are not, then two methods are simply overloaded
166
Methods declared as final cannot be overridden
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Normally Java resolves calls to methods dynamically, at
run time (late binding)
Since, final methods cannot be overridden, a call to one
can be resolved at compile time (early binding)
167
final keyword before a class declaration prevents it from
being inherited
Declaring a class as final implicitly declares all of its methods
as final
final class A {
// ...
}

// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}

168

This feature enables us to re use the objects (functions,
variables)


Write Once, Use Any where, any number of times


Since functions are independent piece of code, they can be
used any number of times


Final classes

Abstract classes

String Class




17
0
17
1
Parent
Child
Inherited
capability
Final and Abstract Classes
All methods and variables can be overridden by default in
subclasses.

This can be prevented by declaring them as final using the
keyword final as a modifier. For example:
final int marks = 100;
final void display();

This ensures that functionality defined in this method cannot
be altered any. Similarly, the value of a final variable cannot
be altered.
17
2
We can prevent an inheritance of classes by other classes by
declaring them as final classes.

This is achieved in Java by using the keyword final as follows:
final class Marks
{ // members
}
final class Student extends Person
{ // members
}

Any attempt to inherit these classes will cause an error.
17
3
The word abstract literally means
INCOMPLETE

Now in the Concept of Programming we may have
incomplete methods of classes.
i abstract methods
ii abstract class

Definition: The methods that does not have any method
body ( that is the method definiton) are called abstract
methods.

abstract <data type> method-name(parameter-list);

any class that contains one or more than one abstract
methods must also be declared abstract .To declare a
class abstract ,you simple use the abstract keyword in
front of the class keyword at the beginning of the class
declaration.

Abstract Classes may contain abstract methods. They are
capable to contain abstract methods.

Inheritance of the abstrsct classes is possible.

An Abstract class cannot be instantiated objects cannot be
created.

What about the object of abstract classes?
There can not be any object of any Abstract Classes.
i.e-An abstract class can not be directly instantiated with the
new operator

Why?
As the abstract class is not fully defined..


SOME FACTS ABOUT ABSTRACT CLASS:
We can not declare abstract constructors


We can not declare abstract static methods


Any sub class of an abstract class must either implement all the
abstract methods in the super class or be itself a abstract
method

abstract class ClassName
{
...

abstract Type MethodName1();


Type Method2()
{
// method body
}
}
When a class contains one or more abstract methods, it
should be declared as abstract class.
The abstract methods of an abstract class must be defined in
its subclass.
We cannot declare abstract constructors or abstract static
methods.
17
9

A class with one or more abstract methods is automatically
abstract and it cannot be instantiated.

A class declared abstract, even with no abstract methods can
not be instantiated.

A subclass of an abstract class can be instantiated if it
overrides all abstract methods by implementation them.

A subclass that does not implement all of the superclass
abstract methods is itself abstract; and it cannot be
instantiated.
18
0
Every string you create is actually an object of type String.
Even string constants are actually String objects

String objects are immutable; once a String object is created,
its contents cannot be altered

Java defines a peer class of String, called StringBuffer, which
allows strings to be altered

One way to create a string is:
String mystring=this is a test

+ operator is used to concatenate two strings
181

equals( ) is used to test two string for equality

length( ) is used to obtain the length of string

charAt( ) is used to obtain the character at a specified index
within a string

Also you can have arrays of string
String str[ ]={one, two, three};
182
183
If you do not want (properties of) your class to be extended
or inherited by other classes, define it as a final class.
Java supports this is through the keyword final.
This is applied to classes.

You can also apply the final to only methods if you do not
want anyone to override them.

If you want your class (properties/methods) to be extended
by all those who want to use, then define it as an abstract
class or define one or more of its methods as abstract
methods.
Java supports this is through the keyword abstract.
This is applied to methods only.
Subclasses should implement abstract methods; otherwise,
they cannot be instantiated.
18
4


Understanding the concepts of :

Introduction to Package
Creating package
Importing package
Using package in java programs







18
5
Contents

Packages:

Putting Classes Together





18
6
18
7
The features in basic form limited to reusing the classes
within a program.

What if we need to use classes from other programs without
physically copying them into the program under development
?

In Java, this is achieved by using what is known as packages,
a concept similar to class libraries in other languages.


Packages are Javas way of grouping a number of related
classes and/or interfaces together into a single unit. That
means, packages act as containers for classes.

The benefits of organising classes into packages are:

The classes contained in the packages of other
programs/applications can be reused.
Classes in packages can be hidden if we dont want other
packages to access them.
Packages also provide a way for separating design from
coding.


18
8


package
System packages
Ex:
java.lang.*
java.util.*
java.io.*
java.sql.*
User Defined
Packages
Created by user .
We have to follow
some steps .
package
Key word is used
to create a
package
Types of packages
Java provides a large number of classes groped into different
packages based on their functionality.
The six foundation Java packages are:
java.lang
Contains classes for primitive types, strings, math
functions, threads, and exception
java.util
Contains classes such as vectors, hash tables, date etc.
java.io
Stream classes for I/O
java.awt
Classes for implementing GUI windows, buttons, menus
etc.
java.net
Classes for networking
java.applet
Classes for creating and implementing applets
19
0
The packages are organised in a hierarchical structure. For
example, a package named java contains the package awt,
which in turn contains various classes required for
implementing GUI (graphical user interface).
19
1
Graphics
Font
java
Image

awt
lang
java Package containing
lang, awt,.. packages;
Can also contain classes.
awt Package containing
classes
Classes containing
methods

There are two ways of accessing the classes stored in
packages:
Using fully qualified class name
java.lang.Math.sqrt(x);
Import package and use class name directly.
import java.lang.Math
Math.sqrt(x);
Selected or all classes in packages can be imported:






Implicit in all programs: import java.lang.*;
package statement(s) must appear first

19
2
import package.class;
import package.*;
Java supports a keyword called package for creating user-
defined packages. The package statement must be the first
statement in a Java source file (except comments and white
spaces) followed by one or more classes.








Package name is myPackage and classes are considred as
part of this package; The code is saved in a file called
ClassA.java and located in a directory called myPackage.
19
3
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}
Classes in one ore more source files can be part of the same
packages.

As packages in Java are organised hierarchically, sub-
packages can be created as follows:
package myPackage.Math
package myPackage.secondPakage.thirdPackage

Store thirdPackage in a subdirectory named
myPackage\secondPackage. Store secondPackage and
Math class in a subdirectory myPackage.
19
4

As indicated earlier, classes in packages can be accessed
using a fully qualified name or using a short-cut as long as
we import a corresponding package.

The general form of importing package is:

import package1[.package2][].classname
Example:
import myPackage.ClassA;
import myPackage.secondPackage
All classes/packages from higher-level package can be
imported as follows:
import myPackage.*;
19
5

Let us store the code listing below in a file named
ClassA.java within subdirectory named myPackage within
the current directory (say abc).
19
6
package myPackage;
public class ClassA {
// class body
public void display()
{
System.out.println("Hello, I am ClassA");
}
}
class ClassB {
// class body
}
Within the current directory (abc) store the following code in
a file named ClassX.java
19
7
import myPackage.ClassA;

public class ClassX
{
public static void main(String args[])
{
ClassA objA = new ClassA();
objA.display();
}
}

When ClassX.java is compiled, the compiler compiles it and
places .class file in current directly. If .class of ClassA in
subdirectory myPackage is not found, it comples ClassA
also.


Note: It does not include code of ClassA into ClassX


When the program ClassX is run, java loader looks for
ClassA.class file in a package called myPackage and loads it.
19
8

Let us store the code listing below in a file named
ClassA.java within subdirectory named secondPackage
within the current directory (say abc).
19
9
package secondPackage;
public class ClassC {
// class body
public void display()
{
System.out.println("Hello, I am ClassC");
}
}
Within the current directory (abc) store the following code in
a file named ClassX.java
20
0
import myPackage.ClassA;
import secondPackage.ClassC;
public class ClassY
{
public static void main(String args[])
{
ClassA objA = new ClassA();
ClassC objC = new ClassC();
objA.display();
objC.display();
}
}
[raj@mundroo] package % java ClassY

Hello, I am ClassA
Hello, I am ClassC

[raj@mundroo] package %
20
1

All classes (or interfaces) accessible to all others in the same
package.

Class declared public in one package is accessible within
another. Non-public class is not

Members of a class are accessible from a difference class, as
long as they are not private

protected members of a class in a package are accessible to
subclasses in a different class
20
2

Public keyword applied to a class, makes it available/visible
everywhere. Applied to a method or variable, completely
visible.

Private fields or methods for a class only visible within that
class. Private members are not visible within subclasses, and
are not inherited.

Protected members of a class are visible within the class,
subclasses and also within all classes that are in the same
package as that class.
20
3
20
4
Accessible to: public protected Package
(default)
private
Same Class
Yes Yes Yes Yes
Class in package
Yes Yes Yes No
Subclass in
different package
Yes Yes No No
Non-subclass
different package
Yes No No No
Consider an existing package that contains a class called
Teacher:







This class is stored in Teacher.java file within a directory
called pack1.

How do we a new public class called Student to this
package.
20
5
package pack1;
public class Teacher
{
// class body
}
Define the public class Student and place the package
statement before the class definition as follows:







Store this in Student.java file under the directory pack1.

When the Student.java file is compiled, the class file will be
created and stored in the directory pack1. Now, the package
pack1 will contain both the classes Teacher and Student.
20
6
package pack1;
public class Student
{
// class body
}
class Teacher
package pack1;
class Student
When packages are developed by different organizations, it is
possible that multiple packages will have classes with the same
name, leading to name classing.







We can import and use these packages like:
import pack1.*;
import pack2.*;
Student student1; // Generates compilation error
20
7
class Teacher
package pack1;
class Student
class Student
package pack2;
class Courses

In Java, name classing is resolved by accessing classes with
the same name in multiple packages by their fully qualified
name.

Example:
import pack1.*;
import pack2.*;
pack1.Student student1;
pack2.Student student2;
Teacher teacher1;
Courses course1;
20
8
A new class called Professor can be created by extending
the Teacher class defined the package pack1 as follows:
20
9
import pack1.Teacher;
public class Professor extends Teacher
{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class.
}

Packages allow grouping of related classes into a single
united.

Packages are organised in hierarchical structure.

Packages handle name classing issues.

Packages can be accessed or inherited without actual copy of
code to each program.
21
0

+ Introduction about interface

+Defining an interface

+Use of interface?

+Different between interface and abstract class




21
1
Contents
21
2
212
Interfaces
Design Abstraction and a way for
loosing realizing Multiple Inheritance
Interface is nothing but a prototype
Interface is a conceptual entity similar to a Abstract class.
Can contain only constants (final variables) and abstract
method (no implementation) - Different from Abstract classes.
Use when a number of classes share a common interface.
Each class should implement the interface.
Using the keyword interface.
Interfaces are fully abstract.

21
3
An interface is basically a kind of classit contains methods
and variables, but they have to be only abstract classes and
final fields/variables.

Therefore, it is the responsibility of the class that
implements an interface to supply the code for methods.

A class can implement any number of interfaces, but cannot
extend more than one class at a time.

Therefore, interfaces are considered as an informal way of
realizing multiple inheritance in Java.
21
4
2
1
5
speak()
Politician Priest
<<Interface>>
Speaker
speak() speak()
Lecturer
speak()
Syntax (appears like abstract class):






Example:



21
6
interface InterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration only method body
}
interface Speaker {
public void speak( );
}

Interfaces are used like super-classes who properties are
inherited by classes. This is achieved by creating a class that
implements the given interface as follows:
21
7
class ClassName implements InterfaceName [, InterfaceName2, ]
{
// Body of Class
}
21
8
class Politician implements Speaker {
public void speak(){
System.out.println(Talk politics);
}
}
class Priest implements Speaker {
public void speak(){
System.out.println(Religious Talks);
}
}
class Lecturer implements Speaker {
public void speak(){
System.out.println(Talks Object Oriented Design and Programming!);
}
}

Like classes, interfaces can also be extended. The new sub-
interface will inherit all the members of the superinterface in
the manner similar to classes. This is achieved by using the
keyword extends as follows:

21
9
interface InterfaceName2 extends
InterfaceName1 {
// Body of InterfaceName2
}
A general form of interface implementation:







This shows a class can extended another class while
implementing one or more interfaces. It appears like a
multiple inheritance (if we consider interfaces as special kind
of classes with certain restrictions or special features).
22
0
class ClassName extends SuperClass implements InterfaceName [,
InterfaceName2, ]
{
// Body of Class
}
Consider a university where students who participate in the
national games or Olympics are given some grace marks.
Therefore, the final marks awarded = Exam_Marks +
Sports_Grace_Marks. A class diagram representing this
scenario is as follow:
22
1
Student Sports
Exam
Results
extends
extends
implements
class Student
{
// student no and access methods
}
interface Sport
{
// sports grace marks (say 5 marks) and abstract methods
}
class Exam extends Student
{
// example marks (test1 and test 2 marks) and access methods
}
class Results extends Exam implements Sport
{
// implementation of abstract methods of Sport interface
// other methods to compute total marks =
test1+test2+sports_grace_marks;
// other display or final results access methods
}
22
2
interface A{
void display();
}
interface B extends A{
void show();
}
class C implements B{
void display(){
System.out.println(interface A);
}
void show(){
System.out.println(Interface B);
}
}
class D
{
public static void main(String arr[])
{
C c=new C();
c.display();
c.show();
}
}

Like abstract class,
1. if a class implement an interface, you have to override the
interfaces methods in the class.
2. You cannot create instances from an interface by using new
operator.
3. Interface can be a type as well.
Runnable r;
4. the purpose of creating interface is because of
polymorphism.

224

Unlike abstract class,
1. You can have multiple interface in one class. To implement
those interfaces, use implements keyword and separate
interfaces by comma.
public class Test implements Runnable, ActionListener,
MouseMotionListener {
/* Overridden interfaces methods */
}
2. Interface uses interface keyword.
3. Interface is NOT designed to be superclass. Interface is
designed to add some behaviors to a class.
225

4. In the relationships, we say that:
4.1. A relationship between class/abstract class and class is
a strong relationship. It is known as IS-A relationship.
E.g: A duck is a bird. It clearly means the duck is really a
bird. So the bird can be a superclass of a duck. It could be
either concrete or abstract class.
4.2. A relationship between class and interface is a weak
relationship. It is known as Is-kind-of relationship.
E.g: A duck is flyable. Flyable can never ever be the
superclass of the duck. It just means this duck can fly. So
flyable is interface.
226


+ An interface is a collection of abstract methods and
constants. A class implements an interface by
declaring it in its implements clause, and providing
a method body for each abstract method.
One benefit of using interfaces is that they
simulate multiple inheritance.

22
7

To explain Exception in java

Show how programmer-defined exceptions are created,
thrown and caught

To provide the concepts of exception handling

Explain the use of try, catch, finally, throw, throws keywords.





22
8

The compilation process will detect programming mistakes
such as syntax errors and type mismatches. Such errors can
therefore be referred to as compilation errors.


But once code is compiled and running, it will have to face the
real world of erroneous input, inexistent files, hardware
failure Such problems are commonly known as runtime
errors, which are likely to cause the program to abort.

22
9
An exception is a condition that is caused by a runtime error
in the program.

Need of Exception Handling

If a program does not handle the exception at all, the
program will terminate abnormally and produce a message
that describes what exception occurred, and where it was
produced.

The purpose of exception handling is to provide a means to
detect and report an exceptional circumstance so that
appropriate action can be taken.


Learning about Exceptions

Exception- An unexpected or error condition
- For example:
You issue a command to read a file from a disk, but the file does not exist

You write data to a disk but the disk is full or unformatted
User enters invalid data

The program attempts to divide by zero

Common Java Exceptions

ArithmeticException

ArrayIndexOutOfBoundException

ArrayStoreException

FileNotFoundException

IOException - general I/O failure
NullPointerException - referencing a null object

OutOfMemoryException

SecurityException - when applet tries to perform an action not allowed by the
browsers security setting.

StackOverflowException

StringIndexOutOfBoundException

2


A Java exception is an object that describes an exceptional
condition that has occurred in a piece of code

When an exceptional condition arises, an object representing
that exception is created and thrown in the method that
caused the error

An exception can be caught to handle it or pass it on

Exceptions can be generated by the Java run-time system, or
they can be manually generated by your code
Java exception handling is managed by via five keywords: try, catch,
throw, throws, and finally
Program statements to monitor are contained within a try block
If an exception occurs within the try block, it is thrown
Code within catch block catch the exception and handle it
System generated exceptions are automatically thrown by the
Java run-time system
To manually throw an exception, use the keyword throw
Any exception that is thrown out of a method must be specified
as such by a throws clause
233

The exception handling mechanism suggests a
separate error handling code that performs the
sequence of tasks like

Find the problem (Hit the exception)
Inform that an error has occurred (Throw the exception)
Receive the error information (Catch the exception)
Take the corrective actions (Handle the exception.)
23
4
23
5
try Block
Statements that causes
an exception
catch Block
Statements that
handle the exception
Throws
exception
Object
Any code that absolutely must be executed before a method
returns is put in a finally block
General form of an exception-handling block
try{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb){
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb){
// exception handler for ExceptionType2
}
//
finally{
// block of code to be executed before try block ends
}

If an exception is not caught by user program, then execution
of the program stops and it is caught by the default handler
provided by the Java run-time system
Default handler prints a stack trace from the point at which
the exception occurred, and terminates the program
Ex:
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Output:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Exception in thread "main"



Handling an exception has two benefits,

It allows you to fix the error
It prevents the program from automatically terminating

The catch clause should follow immediately the try block

PROGRAM:
Output:
Division by zero.
After catch statement.

If more than one can occur, then we use multiple catch
clauses

When an exception is thrown, each catch statement is
inspected in order, and the first one whose type matches that
of the exception is executed

After one catch statement executes, the others are bypassed

EXAMPLE PROGRAM
Program Output

If no command line argument is provided, then you will see
the following output:
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks
If any command line argument is provided, then you will see
the following output:
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.

Remember that, exception subclass must come before any of
of their superclasses

Because, a catch statement that uses a superclass will catch
exceptions of that type plus any of its subclasses. So, the
subclass would never be reached if it come after its
superclass

For example, ArithmeticException is a subclass of Exception

Moreover, unreachable code in Java generates error
Multiple Catch Statements (Contd.): Catch-all block


Catch-all block
- Accepts more generic Exception argument type
catch(Exception e)
- Good approach to handle multiple exception throws by a code block

public class TwoMistakes3

{ public static void main(String[] args)
{ int num[] = {4, 0, 0};

try

{ num[2] = num[0] / num[1];
num[2] = num[3] / num[0];
}
catch( Exception e) // multiple exceptions can be handle by this block

{ System.out.println(e.getMessage());
}
}
}

14

EXAMPLE PROGRAM
Throwing an Exception

Throw
- Mostly exceptions are implicitly thrown by the Java run-time system

- Programmers can throw an exception explicitly too
throw ThrowableInstance;

//ThrowableInstance must be the object of class which is derived from Throwable

e.g. throw new MyException();

derived from

When exception thrown

- Control exits current try block

Throwable

- Proceeds to catch handler (if exists)

21

Preceding step
try block

throw
statement

unmatched catch
matching catch
unmatched catch
next step
EXAMPLE PROGRAM
Example: Throw Statement
class ThrowDemo

{ static void demoproc()
{
try
{

Output:

Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");

throw e; // re-throw the exception
}
}

public static void main(String args[])
{
try
{
//Re-throwing
demoproc();
}
catch(NullPointerException e)
{ System.out.println("Recaught: " + e); }
}
}

248
Output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

It is used to handle premature execution of a method (i.e. a
method open a file upon entry and closes it upon exit)

finally creates a block of code that will be executed after
try/catch block has completed and before the code following
the try/catch block

finally clause will execute whether or not an exception is
thrown

249
250
Preceding step
try block

throw
statement

unmatched
catch
matching catch
unmatched
catch
next step
finally
try
{
..
..
.
}
finally
{
..
..
.
}
try
{
..
..
.
}
catch(.)
{ . }
catch(..)
{ . }
..
..
finally
{
..
..
}
Finally Example Program
25
2

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, then the next
try statements catch handlers are inspected for a match

If a method call within a try block has try block within it, then
then it is still nested try

try
{
try
{

}
catch(Exception e)
{
}
}
catch(Exception e)
{

}
Example Program

If a method is capable of causing an exception that it does
not handle, it must specify this behavior so that callers of the
method can guard themselves against that exception.

We do this by including a throws clause in the methods
declaration.

A throws clause lists the types of exceptions that a method
might throw. All the exceptions that a method can throw
must be declared in the throws clause.

If they are not handled by callers of the method a compile-
time error will occur.

255

FORMAT:

type mthod-name(parameter list) throws exception-list
{
//body of method.
}
Example Program
25
6

Java has its built-in capability to ensure that exceptions are
handled within the java program.
Exceptions handled by:

Programmer

JVM(Java Runtime System)
25
8
Object
Throwable
Error
LinkageError
ThreadDeath
VirtualMachineError
AWTError
Exception
RunTimeException
ArithmeticException
IndexOutOfBoundsException
NullPointerEXception
IllegaAccessException
NoSuchMethodException
ClassNotFoundException
Throwable
The base class for all exceptions, it is required for a class to be
the rvalue to a throw statement.
Error
Any exception so severe it should be allowed to pass uncaught
to the Java runtime.
Exception
Anything which should be handled by the invoker is of this type,
and all but five exceptions are.
Checked Exceptions Unchecked Exceptions
Checked exceptions inability to acquire system
resources (such as insufficient memory, file does not
exist)
Java checks at compile time that some mechanism is explicitly in
place to receive and process an exception object that may be created
during runtime due to one of these exceptions occurring.
Unchecked exceptions exceptions that occur because of the user
entering bad data, or failing to enter data at all.
Unchecked exceptions can be avoided by writing more robust code that
protects against bad input values. Java does not check at compile time
to ensure that there is a mechanism in place to handle such errors.
Java Built-in Exceptions: Checked Exceptions

Table: Javas Checked Exceptions defined in java.lang

Exception Meaning
ClassNotFoundException Class not found
CloneNotSupportedException

Attempt to clone an object that does not implement
the Cloneable interface.

IllegalAccessException Access to a class is denied.
InstantiationException

Attempt to create an object of an abstract class or
interface.

InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Java Built-in Exceptions: Unchecked Exceptions

Table: Javas Unchecked RuntimeException Subclasses

Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds
ArrayStoreException Assignment to an array element of an incompatible type
ClassCastException Invalid cast
IllegalArgumentException Illegal argument used to invoke a method
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread
IllegalStateException Environment or application is in incorrect state
IllegalThreadStateException Requested operation not compatible with current thread state
IndexOutOfBoundsException Some type of index is out-of-bounds
NegativeArraySizeException Array created with a negative size
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric format
SecurityException Attempt to violate security
StringIndexOutOfBounds Attempt to index outside the bounds of a string
UnsupportedOperationException An unsupported operation was encountered
20

We can also create our own exceptions specific to our
applications.
It is quite easy, just we create a class by extending
Exception class.
Since it is user defined we must tell the situation
where it will be occurred and the exception object
must be created and throw by ourselves.
26
3
Problem Statement :
Consider the example of the Circle class
Circle class had the following constructor

public Circle(double radius)
{
r = radius;
}


How would we ensure that the radius is not zero
or negative?
26
4
26
5
import java.lang.Exception;
class InvalidRadiusException extends Exception {

public InvalidRadiusException (String msg){
super(msg);
}
}
26
6
class Circle {
double r;

public Circle (double radius ) {
if (radius <= 0 ) {
throw new InvalidRadiusException
(invalid radius value);
}
else {
r = radius;
}
}
}
26
7
class CircleTest {
public static void main(String[] args){
try{
Circle c1 = new Circle(-1);
System.out.println("Circle created");
}
catch(InvalidRadiusException e)
{
System.out.println(e.getMessage());
}
}
}

Example
26
8
Multitasking:
refers to a computer's ability to perform multiple jobs concurrently
Multitasking is divided into two types:

Process-based: Here two or more programs runs concurrently. You can
run Windows calculator and a Text editor (Notepad) at the same time.

Thread-based: A single program can perform two or more tasks
simultaneously. For example, text editor can print while formatting is
being done.
more than one program are running concurrently
270
O A thread is a single sequential flow of control
within a program.
O Thread does not have its own address space but
uses the memory and other resources of the
process in which it executes.
O There may be several threads in one process
O The Java Virtual Machine (JVM) manages these
and schedules them for execution.


A thread is a single sequence of execution within
a program

refers to multiple threads of control within a
single program

each program can run multiple threads of control
within it, e.g., Web Browser


Multithreading enables programmers to do multiple
things at one time.

For ex, we can send tasks such as printing into the
background and continue to perform some other
task in the foreground.


276
CPU CPU1 CPU2
277
CPU
Process 1 Process 3 Process 2 Process 4
main
run
GC
Processes & Threads
4: Threads
27
9
THREADS
When multiple events/actions need to occur
at the same time
Examples:
Download 10 pages.
Single-threaded program: sequentially
Multithreaded: all at the same time save time
Download data from the network and respond to
mouse at the same time
class ABC
{
.
.....
.
.....
.
.....
}
Beginning
Single-threaded
Body of
Execution
End

start

start

start
switching
switching
Main Method
Module
Threads are implemented as objects that contains a method called run()
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
Create a thread:
MyThread thr1 = new MyThread();

Start Execution of threads:
thr1.start();

Create and Execute:
new MyThread().start();



:: Extending the thread class
EXAMPLE
ThreadEx1 .java
284
:: Extending the thread class : example
class MyThread extends Thread { // the thread
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread

class ThreadEx1 { // a program that utilizes the thread
public static void main(String [] args ) {
MyThread t = new MyThread();
// due to extending the Thread class (above)
// I can call start(), and this will call
// run(). start() is a method in class Thread.
t.start();
} // end main()
} // end class ThreadEx1

285
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
Creating Object:
MyThread myObject = new MyThread();

Creating Thread Object:
Thread thr1 = new Thread( myObject );

Start Execution:
thr1.start();



:: Implementing the runnable interface
EXAMPLE
ThreadEx2.java
:: Implementing the runnable interface : example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread

class ThreadEx2 {
public static void main(String [] args ) {
MyThread myObject = new MyThread();
Thread thr1 = new Thread( myObject );
thr1.start();

} // end main()
} // end class ThreadEx2

MultithreadedEXAMPLE
ThreadTest.java
O During the life time of a thread, there are many
states it can enter. They include:
1. Newborn state
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
yield
Newborn
start
stop
stop
stop
suspend
sleep
wait
resume
notify
Blocked
Dead
Running Runnable Active
Thread
New
Thread
Idle Thread
(Not Runnable)
Killed
Thread
290
I/O operation completes
start()
Currently executed
thread
Ready queue
Waiting to be notified
Sleeping
Suspending to be resume
Newly created
threads
When we create a thread object , thread is
born and is said to be newborn state.
At this state we can do the things like
Schedule for running using start() method.
Kill it using stop() method.

291
Newborn
Runnable
State
Dead
State
start
stop
The runnable state means that the thread
is ready for execution and is waiting for
the availability of the processor.
That means the runnable threads has
joined the queue for waiting for execution.
If they have all equal priorities then time
slots will be allocated in a round robin
fashion.
The thread that relinquishes the control
also joins in the queue to wait for its next
turn.
293
...... ......
yield()
Running Thread Runnable Thread
ORunning means that the processor has given
its time to the thread for its execution.
OThe thread runs until it relinquishes control
on its own or it is preempted by a higher
priority thread.
OA running thread may relinquish its control in
one of the following situations:


1. Suspend() and resume() Methods:-
This approach is useful when we want to
suspend a thread for some time due to certain
reason, but do not want to kill it.
Running
Runnable Suspended
suspended
resume
2. Sleep() Method :-
This means that the thread is out of the
queue during this time period. The thread re-enter
the runnable state as soon as this time period is
elapsed.
Running
Runnable
Sleeping
sleep(t)
3. Wait() and notify() methods :- blocked
until certain condition occurs

Running Runnable
Waiting
wait
notify
OA thread is said to be blocked when it is prevented
form entering into the runnable state and
subsequently the running state.
OThis happens when the thread is suspended,
sleeping, or waiting in order to satisfy certain
requirements.
OA blocked thread is considered not runnable but
not dead and therefore fully qualified to run again.

OA running thread ends its life when is has completed
executing its run() method. It is a natural death.
OHowever, we can kill it by sending the stop message
to it at any state thus causing a premature death to
it.
OA thread can be killed as soon it is born, or while it is
running, or even when it is in not runnable
(blocked) condition.

static void sleep(long msec) throws int
erruptedException
static void sleep(long msec, int nsec) t
hrows InterruptedException
static void yield()

Static Methods of the Thread Class
String getName()
int getPriority()
boolean isAlive()
void join() throws InterrupteException
void run()
void setName(String s)
void setPriority(int p)
void start()
Instance Methods of Thread
final void suspend( )
final void resume( )
final void stop( )
final void wait( ) throws
InterruptedException
final void notify( )
final void notifyAll( )
Final Methods
Method Description
1. Void sleep(long msec) causes the current Throws
InterruptedException thread to wait for
msec milliseconds
2. Void sleep(long msec, int nsec) causes the current Throws
InterruptedException to wait for msec
milliseconds
plus nsec nanoseconds
3. Void yield() causes the current
thread to yield
control of the
process to other

4. String getName() returns the name of the
thread.
5. Int getPriority() returns the priority of the
thread
6. Boolean isAlive() returns true if this thread
has been started and has not
Yet died. Otherwise,
returns false.
7. Void join() causes the caller to
wait until Throws InterruptedException this thread
dies.


9. Void run() comprises the body of the
thread. This method is
overridden by
subclasses.
10. Void setName(String s) sets the name of this
thread to s.
11. Void setPriority(int p) sets the priority of this
thread to p.
12. Void start() starts the thread



Sleep() - EXAMPLE
Threadsleep.java
isAlive() & join() - EXAMPLE
Talivejoin.java
OUTPUT
yield() & stop() EXAMPLE

ThreadTestys.java


OUTPUT
Every thread has a priority
When a thread is created, it inherits the
priority of the thread that created it
The threads so far had same default priority
(NORM_PRIORITY) and they are served using
FCFS policy.

306
The priority can be adjusted subsequently
using the setPriority() method
Threadobject.setPriority(intNumber)
The priority of a thread may be obtained using
getPriority()
Priority constants are defined:
MIN_PRIORITY=1
MAX_PRIORITY=10
NORM_PRIORITY=5

IIIegalArgaumentException
307
EXAMPLE

ThreadPr.java
- Some of the constructors for Thread are as follows:
Thread()
Thread(Runnable r)
Thread(Runnable r, String s)
Thread(String s)
- Here, r is a reference to an object that implements
the Runnable interface and s is a String used to
identify the thread.

Use of thread constructor using runnable
interface EXAMPLE
Threadconst.java
Use of thread constructor using extends
thread class EXAMPLE
ExtendThreadc.java


Problem: two threads try to modify the same
data (critical section)
Solution: object locking
A method or piece of code in critical section is
declared using synchronized keyword
Each object has a lock
311
Bank Account
deposit()
t1 t2 t3
Applications Access to Shared Resources need to
be coordinated.
Printer (two person jobs cannot be printed at the same
time)
Simultaneous operations on your bank account
Can the following operations be done at the same time
on the same account?
Deposit()
Withdraw()
Enquire()

312
If one thread tries to read the data and
other thread tries to update the same data,
it leads to inconsistent state.
This can be prevented by synchronising
access to the data.
Use Synchronized methods:

public synchronized void update()
{

}
313
Correctly synchronizing threads is one of the more challenging
thread-related skills for Java developers to master.

1. Two or more threads accessing the same data
simultaneously may lead to loss of data integrity. In order to
avoid this java uses the concept of monitor. A monitor is an
object used as a mutually exclusive lock.

2. At a time only one thread can access the Monitor. A second
thread cannot enter the monitor until the first comes out. Till
such time the other thread is said to be waiting.

3. The keyword Synchronized is used in the code to enable
synchronization and it can be used along with a method.

OExample of Synchronization
Synch.java
Ocmd
316
deposit()
aliceAccount
bobAccount
t1 t2
deposit()
?
transfer()
withdraw()
transfer()
withdraw()
- Deadlock is an error that can be encountered in
multithreaded programs.
- It occurs when two or more threads wait for ever for
each other to relinquish locks.
- Assume that thread1 holds lock on object1 and waits
for a lock on object2. thread2 holds a lock on object2
and waits for a lock on object1. neither of these
threads may proceed. Each waits forever for the
other to relinquish the lock it needs.
- Deadlock situations can also arise that involve more
than two threads. Assume that thread1 waits for a
lock held by thread2. thread2 waits for a lock held by
thread3. thread3 waits for a lock held by thread1.

You might also like