Vous êtes sur la page 1sur 80

OVERVIEW OF JAVA

-Ankita R Karia
1/22/14 1ANKITA R KARIA, SFIT, Mumbai
HISTORY OF JAVA

Java is an object-oriented programming language developed initially by


James Gosling and colleagues at Sun Microsystems.

Te language! initially called "a# $named a%ter te oa# trees outside


Gosling&s o%%ice'! (as intended to replace )**.

+o(ever! tey soon discovered tat tere (as already a programming


language called "a#! so tey canged te name to Java
1/22/14 2ANKITA R KARIA, SFIT, Mumbai
C++ vs. JAVA
Java C++
Java is a true and complete object
oriented language.
)** is an e,tension o% ) (it object
oriented beavior. )** is not a complete
object oriented language as tat o% Java.
Java does not provide template classes. )** o%%ers Template classes.
Java supports multiple ineritance using
inter%ace.
)** acieves multiple ineritance by
permitting classes to inerit %rom multiple
classes.
Java does not provide global variables. Global variables can be declared in )**.
Java does not support pointers. )** supports pointers.
-n Java! destruction o% objects is
per%ormed in %inali.e metod.
-n )**! destruction o% objects is per%ormed
by destructor %unction.
Java doesn/t provide eader %iles. )** as eader %iles.
1/22/14 3ANKITA R KARIA, SFIT, Mumbai
PRIMITIVE DATA TYPES
INTEGER TYPES

J010 supports 4 types o%


integers.

Tey are byte, short, int,


long.
FLOATING POINT TYPES

+olds number containing


%ractional parts.

Tey are2-
float- single precision
double-double precision.

3loating point numbers are


treated as double-precision
4uantities.

To %orce tem in single-precision


mode! (e must append % or 3 to
te number.
$ 1.25%! 6.7843)

TYPE SIZE RANGE
byte 1 -128 to 127
short 2 -32768
to
32767
int 4 -2,147,483,648
to
2,147,483,648
long 8
1/22/14 4ANKITA R KARIA, SFIT, Mumbai
PRIMITIVE DATA TYPES
CHARACTER TYPES

J010 supports a
caracter data type called
char.

-t si.e is o% 2 bytes.

9ut! it olds only a single


caracter
BOOLEAN TYPES

-s used (en (e (ant to


test a particular condition
during te e,ecution o% te
program.

:enoted by #ey(ord
boolean.

;ses only 1 bit o% storage.

"%ten used in selection and


iteration statements

PRIMITIVE DATA
TYPES
byte, short, int, long,
float, double, char,
boolean
1/22/14 5ANKITA R KARIA, SFIT, Mumbai
-
Synta,2-
final type symbolic<name = value>
-
Ta#e same name %orm as variable names! 9ut are (ritten in capitals
-
Sould not be assigned any oter value (itin te program a%ter
declaration.
-
0re declared %or types
-
)annot be declared inside a metod. Sould be used as data member in
te beginning o% te class.
SYMBOLIC CONSTANTS
$-ts not mandatory'.
?,ample2- %inal %loat @-=5.1417A>
1/22/14 6ANKITA R KARIA, SFIT, Mumbai
-
;sed (en u need to store a value o% one type into
variable o% oter type.
-
Synta,2-
type variable1 = $type' variable2>
-
Te process o% converting one data type to anoter is
called )0ST-BG.
-
?,amples2-
int m=7C>
byte n = $byte'm>
long count = $long'm>
-
)asting is o%ten necessary (en a metod returns a type
di%%erent tan one (e re4uire.
TYPE CASTING
1/22/14 7ANKITA R KARIA, SFIT, Mumbai
-
-t is possible to assign a value o% one type to a variable o% a
di%%erent type (itout a cast.
-
J010 does te conversion o% te assigned value automatically.
-
Tis is #no(n as AUTOMATIC CONVERSION.
-
-t is possible only i% te destination type as enoug precision to
store te source values.
-
WIDENING/PROMOTION:- Te process o% assigning a
smaller type to larger one.

NARROWING:- 1ice versa o% Didening


Automatic Conversion
1/22/14 8ANKITA R KARIA, SFIT, Mumbai
-
J010 permits mi,ing o% constants and variables o% di%%erent
types in an e,pression! but during evaluation it aderes to
very strict rules o% type conversion.
-
-% operands are o% di%%erent types! te Elo(erF type is
automatically converted to EigerF type be%ore te operation
proceeds. Te result is o% iger type.
-
Te %inal result o% an e,pression is converted to te type o%
te variable on te le%t o% te assignment be%ore assigning te
value
TYPE CONVERSIONS IN
EXPRESSION
1/22/14 9ANKITA R KARIA, SFIT, Mumbai
-
J010 supports basic mat %unctions troug Mat class
de%ined in te java.lang.pac#age.
-
Te %unctions sould be used as %ollo(s2-
Mat.%unction<name$'>
-
?,ample2 y = Mat.s4rt$,'>
MATHEMATICAL FUNCTIONS
3unction
name
java.lang.Mat
10 1/22/14 ANKITA R KARIA, SFIT, Mumbai
G?T;GB
TH@?
3;B)T-"BS
0)T-"B
double sin$double ,' Geturns te sine o% te angle , in radians
int abs $int a' Geturns te absolute value
double ceil$double ,' Geturns te smallest (ole no. $> / = !
double s4rt$,' Geturns s4uare root o% ,
int min$int a! int b' Geturns minimum o% a and b
double po($,!y' Geturns ,y
double e,p$,' Geturns e,
double log$,' Geturns te natural logaritm o% ,
int ma,$a!b' Geturns ma,imum o% a and b
double "a#$%& Gounds to te nearest (ole number
11 1/22/14 ANKITA R KARIA, SFIT, Mumbai
COMMAND LINE ARGUMENTS
1st arument
!n" arument
1/22/14
ANKITA R KARIA, SFIT,
Mumbai
1
12
COMMAND LINE ARGUMENTS
1
0re parameters tat are supplied to te application program at te
time o% invo#ing it %or e,ecution.
1
0rguments are to be given (en you G;B your program.
?,ample2 java comm '( ')
Comman" Line
Arument
s
0ssigned to a""a* a"+,
as %ollo(s
14 = = args [0]
1 = = args[1]
1/22/14
ANKITA R KARIA, SFIT,
Mumbai
13
-
J010 allo(s objects to initiali.e temselves (en tey are
created
CONSTRUCTOR
PROPERTIES:-
-nitiali.es an object immediately upon creation.
Same name as te class in (ic it resides and syntactically similar
to a metod.
-s called automatically a%ter te object is created.
:oes not ave return type.
?I0M@J?
1/22/14 15 ANKITA R KARIA, SFIT, Mumbai
B" G?T;GB TH@?
";T@;T
1/22/14 16 ANKITA R KARIA, SFIT, Mumbai
-
Metods ave same name! but di%%erent parameter list .
-
-s used (en objects are re4uired to per%orm similar tas#s but
using di%%erent input parameters.
-
0lso #no(n as POLYMORPHIM.
-
+ere! te aim is to provide several metod de%initions all (it
same name! but di%%erent parameter lists.
-
Te di%%erence may eiter in number or type o% arguments
Methods return type does not play any role
in this
1/22/14 17 ANKITA R KARIA, SFIT, Mumbai
-
-n addition to overloading metods! you can also
overload constructor metod
E-AMPLE
OVERLOADING CONSTR#CTORS
class )ons
K
)ons$%loat r'
K
L
)ons$int b! int l'
K
L
1/22/14 18 ANKITA R KARIA, SFIT, Mumbai
STATIC MEMBERS

Is used to define a member that is common to all objects and accessed without using a articular object!

Thus member belongs to the class as a whole rather than the objects created from the class!

"sed when we want to ha#e a #ariable common to all instances of a class!


SYNTAX:-
static int count;
static int max(int x, int
y)
STT!C M"M#"RS
)lass variables and )lass metods
Referred to as
$%&&%$'
$(
A)*ITA R *ARIA, S+IT, Mumbai
E,AM-.E
$%&&%$'
&/
A)*ITA R *ARIA, S+IT, Mumbai
RESTRICTI0)S +ACE1 B2 STATIC MET301S45

They can only call other static methods!

They can only access static data!

They cannot refer to this or super in any way!


STATIC
MET301S ARE
CA..E1 "SI)6
CLASS NAME
$%&&%$'
&$
A)*ITA R *ARIA, S+IT, Mumbai
CA.. by 7A."E #s! CA.. by RE+ERE)CE
CA.. B2 7A."E CA.. B2 RE+ERA)CE
This method coies the #alue
of an argument into the
formal arameter of the
subroutine
In this method, reference to
an argument is assed to the
arameter!
1oes not access actual
argument
This reference is used to
access the actual argument!
Thus, changes made to
arameter of the subroutine
ha#e no effect on the
argument!
Thus, changes made to
arameter will ha#e an effect
on the argument!
$%&&%$'
&8
A)*ITA R *ARIA, S+IT, Mumbai
EXAMPLE
CALL by VALUE:- Simle
tye arguments are assed
to methods!
CALL by REFERENCE:-
0bjects are assed to
methods
R"M"M#"R
$%&&%$'
&'
A)*ITA R *ARIA, S+IT, Mumbai
REC"RSI0)

9A7A suorts recursion.

Recursion is the rocess of defining something in


terms of itself!

A method that calls itself is said to be recursive.


$%&&%$'
&:
A)*ITA R *ARIA, S+IT, Mumbai
7ISIBI.IT2 C0)TR0.

Visibility modifiers are used to restrict the access to


certain #ariables and methods from outside the class!

Also ;nown as ACCESS MODIFIERS.


7isibility
.abels
PUBLIC
PRIVATE
PROTECTED
$%&&%$'
&<
A)*ITA R *ARIA, S+IT, Mumbai
7ISIBI.IT2 C0)TR0. =Contd!!>
PUBLIC 7isible to entire class in which it is defined and
All the class 0utside
-RI7ATE Enjoys highest degree of rotection!
Accessible only with their own class!
Cannot be inherited, thus not accessible in sub5class!
+riendly ?hen no access modifier is secified then the default
#ersion of ublic accessibility is ;nown as
@+RIE)1.2A
PUBLIC +riendly
Ma;es fields #isible in all
classes, regardless of their
ac;ages
Ma;es fields #isible only in
the same ac;age!
6
r
o
u

o
f
r
e
l
a
t
e
d

c
l
a
s
s
e
s
s
t
o
r
e
d
s
e

a
r
a
t
e
l
y
-R0TECTE1 Its le#el lies between -"B.IC ACCESS B +RIE)1.2
ACCESS!
Ma;es the fields #isible not only to all classes and
subclasses in same ac;age but also to subclasses in
other ac;ages
$%&&%$'
&C
A)*ITA R *ARIA, S+IT, Mumbai
DECLARAING ARRAYS

T!" g"n"ra# $%rm %$ '-$ arra& '"(#arati%n is)-


type *ar+nam"[ ],
int! %loat! car array name
?.g.2--- .#/ ,0%"1, 2 34
scores
N-..
1/ 0*"n t!%ug! an arra& *ariab#"
1s(%r"s2 is '"(#ar"', but t!"r"
is n% arra& a(tua##& "3isting/
2. score is set to NULL, i.e. an
array wit NO VALU!.
T% #ink 4it! a(tua#, 5!&si(a# arra& %$ int"g"rs6/
intMN scores = ne( intM1CN>
1/22/14 27 ANKITA R KARIA, SFIT, Mumbai
29
D105a".#+ A""a*,

Some examples of array declarations:


$%675123 8".01, = #19 $%67512)::34
7%%51a#23 ;5a+,4
;5a+, = #19 7%%51a#2<:34
0=a"23 0%$1, = #19 0=a"2'>):34

8i*ing *a#u"s int% t!" arra& (r"at"' is kn%4n as INITIALI"ATION.

T!" *a#u"s ar" '"#imit"' b& bra("s an' s"5arat"' b& (%mmas

03am5#"s)
intM N units = K146! 525! OA! A55! 74C! 28A! A6! 114! 2AO! 468L>
carM N letterGrades = K&0&! &9&! &)&! &:&! /3&L>

Bote tat (en an initiali.er list is used2

te ne( operator is not used

no si.e value is speci%ied

Te si.e o% te array is determined by te number o% items in te


initiali.er list. 0n initiali.er list can only be used only in te array
declaration
1/22/14 90 ANKITA R KARIA, SFIT, Mumbai

A s5"(i$i( "#"m"nt in an arra& (an b" a(("ss"' b& s5"(i$&ing


its in'"3 4it!in s:uar" bra(k"ts/

A## arra& in'"3"s start at "!RO.


!#a$%&e'( Syste$.o)t.%rint&n*)nits+(,-.
intM N units = K146! 525! OA! A55! 74C! 28A! A6! 114! 2AO!
468L>
: ' < ? ( ) @ > A B
mean = $unitsMCN * unitsM1N'/2>
1/22/14 91 ANKITA R KARIA, SFIT, Mumbai
PROCESSING ARRAY
ELEMENTS

;$t"n a for( ) #%%5 is us"' t% 5r%("ss "a(! %$ t!" "#"m"nts %$


t!" arra& in turn/

T!" #%%5 (%ntr%# *ariab#", i, is us"' as t!" in'"3 t% a(("ss arra&


(%m5%n"nts
!/A01L!'( int i>
%or$i=:>iP=2>i**'
K
System.out.println$*scoreMiN'>
L
92
50 12 45 78 66 100 125
: ' < ? ( ) @
score
score MCN
1/22/14 ANKITA R KARIA, SFIT, Mumbai
int i>
%or$i='>iP=2>i**'
K
System.out.println$*scoreMiN'>
L
50 12 45 78 66 100 125
: ' < ? ( ) @
score
score M1N
1/22/14 99 ANKITA R KARIA, SFIT, Mumbai
94
Bu!"# C$%&'i!(

;n(" an arra& is (r"at"', it !as a $i3"' si<"

An in'"3 us"' in an arra& r"$"r"n(" must s5"(i$& a *a#i'


"#"m"nt

T!at is, t!" in'"3 *a#u" must b" in b%un's =: t% N-'>

T!" ?a*a int"r5r"t"r t!r%4s an


ArrayIndexOutOfBoundsException i$ an arra& in'"3
is %ut %$ b%un's

T!is is (a##"' automatic bounds checking


1/22/14 ANKITA R KARIA, SFIT, Mumbai
9
Bu!"# C$%&'i!(

F%r "3am5#", i$ t!" arra& score (an !%#' ':: *a#u"s, it (an
b" in'"3"' using %n#& t!" numb"rs : /% BB

I$ i !as t!" *a#u" '::, t!"n t!" $%##%4ing r"$"r"n(" 4i##


(aus" an "3("5ti%n t% b" t!r%4n)
System.out.println (score[i]);

It@s (%mm%n t% intr%'u(" off-by-one errors 4!"n using


arra&s
for (int i=0; i <= 100; i++)
score[i] = i*50;
problem
1/22/14 ANKITA R KARIA, SFIT, Mumbai
RR$ %"N&T'
O
In JAVA, all arrays store the allocated size in a variable
named length.
O
It is referenced using the array name:
scores.length
O
Note that length holds the number of elements, not the
largest index.
O
This information will be useful in the manipulation of
arrays when their sizes are not known
36
1/22/14 ANKITA R KARIA, SFIT, Mumbai

Bormally! objects in Java are created (it te new #ey(ord.


OR

+o(ever! String objects can be created QimplicitlyQ2


DECLARING C INITIALISING
String name>
name = ne( String$EMumbaiQ'>
String name>
name = Q)raigQ>
String name= ne( String$EMumbaiQ'>
1/22/14 3) ANKITA R KARIA, SFIT, Mumbai
+
String objects are andled specially by te compiler.
+
String is te only class (ic as QimplicitQ instantiation.
+
Te String class is de%ined in te DavaE5a#+ 8a0Fa+1E
+
Strings are immutable.
+
Te value o% a String object can never be canged.
+
3or mutable Strings! use te String9u%%er class.
The String Class
1/22/14 3* ANKITA R KARIA, SFIT, Mumbai
S+,i!( M%+$"#

Te S/".#+ class contains many use%ul metods %or string-


processing applications.
0 S/".#+ metod is called by (riting a S/".#+ object! a dot! te name o%
te metod! and a pair o% parenteses to enclose any arguments
-% a S/".#+ metod returns a value! ten it can be placed any(ere tat
a value o% its type can be used
S/".#+ +"11/.#+ = GH155%G4
.#/ 0%6#/ = +"11/.#+E51#+/=H4
S*,/1&E%6/E8".#/5#HGL1#+/= ., G + +"11/.#+E51#+/=H4
0l(ays count %rom .ero (en re%erring to te position or index o% a
caracter in a string
String metod
1/22/14 3- ANKITA R KARIA, SFIT, Mumbai
STR!N& #U(("R C%SS

STG-BG9;33?G class creates strings %le,ible lengt tat


can be modi%ied in terms o% bot lengt and content.

STG-BG9;33?G may ave caracters and substrings


inserted in te middle or appended to te end.

STG-BG9;33?G automatically gro(s to ma#e room %or


suc additions
0ctually STG-BG9;33?G as more
caracters pre allocated tan are actually
needed! to allo( room %or gro(t
1/22/14 41 ANKITA R KARIA, SFIT, Mumbai
STR!N& #U(("R
CONSTRUCTORS

S/".#+ B6;;1"H:- Geserves room %ro 18 caracters


(itout reallocation

S/".#+B6;;1"H.#/ ,.I1:- 0ccepts an integer argunent


tat e,plicilty sets te si.e o% te bu%%er

S/".#+B6;;1"HS/".#+ ,/":- 0ccepts STG-BG argument


tat sets te initial contents o% te STG-BG9;33?G and
allocated room %or 18 additional caracters.
1/22/14 42 ANKITA R KARIA, SFIT, Mumbai
STR!N& #U(("R (UNCT!ONS

51#+/=H:-Geturns te current lengt o% te string.

0a8a0./*H:- Geturns te total allocated capacity.

v%.$ 1#,6"1Ca8a0./*H:- @reallocates room %or a certain


number o% caracters.

v%.$ ,1/L1#+/=H.#/ len:- Sets te lengt o% te string s1


to len.
-% lenPs1.lengt$'! s1 is truncated.
-% lenRs1.lengt$'! .eros are added to s1.

0=a"A/H.#/ !here:- ?,tracts value o% a single caracter.

,1/C=a"A/H.#/ !hereJ 0=a" ch:- Sets te value o% caracter


at speci%ied position.
1/22/14 43 ANKITA R KARIA, SFIT, Mumbai
)"CTORS
*+,,+*-
-. N/!T R /R!, S(!T, Mum0ai
Vectors
E
1ector implements a :HB0M-) 0GG0H.
E
1ectors can old objects o% any type and any number.
E
V10/%" 05a,, is contained in DavaE6/.5 8a0Fa+1
E
1ector is di%%erent %rom 0GG0H in t(o (ays2-
1. 1ector is syncroni.ed.
2. -t contains many legacy metods tat are not part o% te
collection %rame(or#.
1. ?numeration.
2. -terator
*+,,+*- -1 N/!T R /R!, S(!T, Mum0ai
Declaring VECTORS
1ector list = ne( 1ector$'>
1ector list = ne( 1ector$int si.e'>
1ector list = ne( 1ector$int si.e! int incr'>
)reates a de%ault vector! (ic
as an initial si.e 1C.
)reates a vector! (ose
initial capacity is speci%ied
by si.e.
)reates a vector! (ose initial capacity is speci%ied
by si.e and (ose increment is speci%ied by incr.
*+,,+*- -2 N/!T R /R!, S(!T, Mum0ai
Vectors (Contd.)
E
0 vector can be declared (itout speci%ying any si.e e,plicitly.
E
0 vector (itout si.e can accommodate an un#no(n number o%
items.
E
?ven (en si.e is speci%ied! tis can be overloo#ed and a di%%erent
number o% items may be put into te vector
!n contrast, n RR$ must 0e
al3ays ha4e its si5e speci6ied7
*+,,+*- -8 N/!T R /R!, S(!T, Mum0ai
$RAPPER CLASSES
E
1ectors cannot andle primitive data types li#e int! %loat! long! car
and double.
E
@rimitive data types may be converted into objects using te
DG0@@?G classes contained in java.lang pac#age.
SIMPLE TYPE WRAPPER CLASSES
boolean 9oolean
car )aracter
double :ouble
%loat 3loat
int -nteger
long Jong
*+,,+*- 9: N/!T R /R!, S(!T, Mum0ai
Con4ertin; <rimiti4e data
types
to O0=ects7
SYNTA- ACTION
-nteger ob=ne( -nteger$i' )onverts primitive integer to -nteger object
3loat ob=ne( 3loat$%' )onverts primitive %loat to %loat object
Con4ertin; O0=ects to
<rimiti4e data types7
SYNTA- ACTION
int i=ob.int1alue$' )onverts -nteger object to primitive integer
%loat %=ob.%loat1alue$' )onverts 3loat object to primitive %loat
*+,,+*- 9* N/!T R /R!, S(!T, Mum0ai
Con4ertin; Num0ers to
Strin;s
Usin; toStrin;() method
SYNTA- ACTION
str=-nteger.toString$i' )onverts primitive integer to string
str=3loat.toString$%' )onverts primitive %loat to string
T%ere are ot%er &ra''er c(asses
met%o"s Re)er Ba(aurusam*
*+,,+*- 9, N/!T R /R!, S(!T, Mum0ai
VECTOR
METHODS
void a$$E51&1#/$"bject ele"ent' Te object speci%ied by ele"ent is
added to te vector
int 0a8a0./*H Geturns te capacity o% te vector
boolean 0%#/a.#,H"bject ele"ent' Geturns /"61 i% 151&1#/ is
contained by te vector! else ;a5,1
void 0%8*I#/%$"bject array#$% Te elements contained in te
invo#ing vector are copied into te
array speci%ied by a""a*23
151&1#/A/$int inde&' Geturns te element at te location
speci%ied by inde&
"bject ;.",/E51&1#/HE Geturns te %irst element in te
vector
*+,,+*- 9> N/!T R /R!, S(!T, Mum0ai
VECTOR
METHODS
void .#,1"/E51&1#/A/$"bject ele"entJ
int inde&'
Adds ele"ent to te vector at te
location speci%ied by inde&
boolean .,E&8/*H Geturns /"61 i% 1ector is empty!
15,1 ;a5,1
"bject 5a,/E51&1#/H Geturns te last element in te
vector
void "1&%v1A55E51&1#/,H ?mpties te vector. 0%ter tis
metod e,ecutes! te si.e o% vector
is .ero.
void "1&%v1E51&1#/A/$int inde&' Gemoves element at te location
speci%ied by inde&
void ,1/E51&1#/A/$"bject ele"ent! int
inde&'
Te location speci%ied by inde& is
assigned ele"ent
*+,,+*- 9- N/!T R /R!, S(!T, Mum0ai
VECTOR
METHODS
void ,1/S.I1$int si'e' Sets the number of elements in the
vector to si'e. If the new size is less
than the old size, elements are lost.
If the new size is larger than the
old, null elements are added
int ,.I1H Geturns te number o% elements
currently in te vector
*+,,+*- 99 N/!T R /R!, S(!T, Mum0ai
"NUM"RT!ON !NT"R(C"
E
?e6ines the methods 0y 3hich you can
enumerate the elements in a collection o6
o0=ects
"9T0-B "B? 0T
T-M?
boolean asMore?lements$' Object
next"lement()
Geturns true (ile tere are
still more elements to e,tract
and %alse oter(ise
Geturns te ne,t object in
enumeration
*+,,+*- 9. N/!T R /R!, S(!T, Mum0ai
TYPES OF INHERITANCE

I#=1"./a#01 a55%9, ,67-05a,,1, /% .#=1"./ a55 /=1 va".a751,


a#$ &1/=%$, %; /=1." 8a"1#/ 05a,,E
A
B
A
B
C
A
B C
S-BGJ?
M;JT-J?1?J
+-?G0G)+-0J
J
0
1
0

d
o
e
s

n
o
t

s
u
p
p
o
r
t

m
u
l
t
i
p
l
e

i
n

e
r
i
t
a
n
c
e
1/22/14 57 ANKITA R KARIA, SFIT, Mumbai
SYNTAX for subclass
05a,, sub(na"e 1!/1#$, ,681"K#a&1
E-AMPLE:-
05a,, A
L
M
05a,, B 1!/1#$, A
L
M
A
B
S-BGJ?
1/22/14 58 ANKITA R KARIA, SFIT, Mumbai
SUBCLASS CONSTRUCTOR

0 subclass constructor is used to construct te instance variables


o% bot te subclass and super class.

Te subclass constructor uses #ey(ord super to invo#e te


constructor metod o% super class.
3"JJ"D-BG )"B:-T-"BS S+";J: 9? S0T-S3-?: D+-J?
;S-BG super S?HD"G:.
). super may only be used (itin a subclass constructor metod.
*. super must appear as te %irst statement (itin subclass
constructor.
5. Te parameters in te super call must matc te order and type
o% te instance variables declared in te superclass.
1/22/14 62 ANKITA R KARIA, SFIT, Mumbai
METHOD OVERRIDING
O
In a class hierarchy, when a method in a subclass has the
same name and return type as a method in super class,
then the method in subclass is said to override the method
in super class.
O
When an overridden method is called from within a
subclass, it will always refer to the version of that method
by subclass.
O
The version of the method defined by the super class will be
hidden.
1/22/14 64 ANKITA R KARIA, SFIT, Mumbai
SOLUTION
O
If you wish to access the superclass version of an
overridden function, then it can be done using
super.
OR
-s te mecanism by (ic a call to an overridden metod
is resolved at G;B-T-M?! rater tan compile time.
1/22/14 66 ANKITA R KARIA, SFIT, Mumbai
SOLUTION
O
UPCASTING = When PARENT class reference
variable refers to CHILD class as object, it is
known as UPCASTING.
1/22/14 67 ANKITA R KARIA, SFIT, Mumbai
<R")"NT!N&
O)"RR!?!N&
1/22/14 68 ANKITA R KARIA, SFIT, Mumbai
Final Variables and Methods
O
It is valid to OVERRIDE all the methods and variables in
subclass.
O
Overriding members of superclass can be prevented by
using final keyword.
O
final has three uses:-
1. Used in creating symbolic constants.
2. Prevents Overriding.
3. Prevents Inheritance
1/22/14 69 ANKITA R KARIA, SFIT, Mumbai
ABSTRACT MET+ODS , CLASSES
O
Works exactly opposite from final keyword.
O
abstract keyword makes it compulsory that a method
must be overridden.
HOW TO USE.
O
abstract keyword is preceded before a method definition.
e.g.:- abstract void display();
O
abstract methods compulsorily should be overridden by
subclasses.
O
abstract methods do not have body (method definition).
O
Any class that contains one or more abstract methods
must also be declared as abstract.
Following conditions should
be satisfied while using
abstract classes.
1. Do not directly instantiate
objects of an abstract
class.
2. Abstract methods of an
abstract class must be
defined in its subclass.
3. Do not declare abstract
constructors or abstract
static methods.
1/22/14 71 ANKITA R KARIA, SFIT, Mumbai
INTER-ACE
1
-nter%ace are syntactically similar to classes! but>
Jac# instance variables!
Metods are declared (itout any body
SYMBOLIC CONSTANTS +final%
#STRCT M"T'O?S
inter%ace I,-.R/01.,0M.
K
variable declaration>
metod declaration>
L
inter%ace Mother
K
String eye<color=E9G"DBF>
void tal#s$'>
L
1/22/14
72
ANKITA R KARIA, SFIT, Mumbai
IMPLEMENTING INTER-ACE
1
-nter%aces are used as ES;@?G)J0SS?SF (ose
properties are inerited by classes..
1
Tus! it is necessary to create a class tat inerits
te given inter%ace.
+O$
05a,, classna"e .&851&1#/, interfacena"e
2
3
3unctions in
inter%ace are by
de%ault EpublicF
D

i
l
e

d
e
%
i
n
i
n
g

%
u
n
c
t
i
o
n
s

i
n

c
l
a
s
s

p
r
e
c
e
d
e

i
t

(
i
t


p
u
b
l
i
c

s
p
e
c
i
%
i
e
r
1/22/14
73
ANKITA R KARIA, SFIT, Mumbai
"xample
Moter
eye<color>
(al#$'>
3ater
comple,ion>
tal#$'>
)ild
air<type
:isplay various %eatures o% cild
1/22/14
74
ANKITA R KARIA, SFIT, Mumbai
I!+%,.a&% / E0am12%
)3
speak()
P2i+i&ia! P,i%#+
44I!+%,.a&%55
S1%a'%,
#1%a'67 #1%a'67
L%&+u,%,
#1%a'67
1/22/14 ANKITA R KARIA, SFIT, Mumbai
INTRODUCTION
1
0n .rror is any une,pected result obtained %rom
a program during e,ecution.
1
.rrors sould be andled by te programmer! to
prevent tem %rom reacing te user.
1/22/14 76 ANKITA R KARIA, SFIT, Mumbai
TYPES OF ERRORS
"RRORS
COM<!%"
@T!M"
RUN
@T!M"
1. Gee!a"e# #ue "$ %A&A '$m(i)e!.
2. *i+()a,+ a)) +,"a- e!!$!+.
3. S(e'i.ie+ "/e )ie umbe! 0/e!e "/e e!!$!
/a+ $''u!!e#.
4. .')a++ .i)e i+ $" '!ea"e# 0/ee1e! a e!!$!
i+ #i+()a,e#.
5. Ge" !i# $. a)) e!!$!+ .$! +u''e++.u)
'$m(i)a"i$ a# '!ea"i2 a ')a++ .i)e.
1. Gee!a"e# 0/e 0e !u a .i)e
2. .')a++ .i)e i+ '!ea"e# +u''e++.u)),.
3. 3+ua)), 2ee!a"e# #ue "$ 0!$2 )$2i'
4R
*ue "$ e!!$!+ )i5e A!!a,I#e-4u"4. 6$u#+.
1/22/14 77 ANKITA R KARIA, SFIT, Mumbai
8$a+ i# a! "AC"<T!ON
1
0n .41.P-IO, is an abnormal condition tat arises
in a code se4uence at run time.
1
-t is a G;B-T-M? error.
1
Most common G;B-T-M? errors are2-

:ividing integer by .ero.

0ccessing an element tat is out o% bounds o% an array.

0ccessing a caracter tat is out o% bounds o% a string.

)onversion bet(een strings and number %ails.


0ritmetic ?,ception.
0rrayinde,outo%bounds ?,ception7
Bumber3ormat?,ception
1/22/14 78 ANKITA R KARIA, SFIT, Mumbai
?I)?@T-"B TH@?S
1
0ll e,ception types are subclasses o% te built-in
class Tro(able.
T+G"D09J?
?I)?@T-"B
?GG"G
17 1i!"ua) ma'/ie e!!$!+
R6#/.&1 E!018/.%#E

0utomatically de%ined %or te


programs tat you (rite.
1/22/14 79 ANKITA R KARIA, SFIT, Mumbai
?,ception +andling
1
0 J010 e,ception is an object tat describes an
e,ceptional condition tat as occurred in a piece o%
code.
1
J010 e,ception andling is managed v.a ) 9%"$,E

/"*E

0a/0=E

/="%9

/="%9,E

;.#a55*E
1/22/14 80 ANKITA R KARIA, SFIT, Mumbai
CREATING THREADS
1/22/14 ANKITA R KARIA, SFIT, Mumbai 81

J010/s multitreading system is built upon te Thread class !its


metods! and its companion interface, Runnable..

Tread class de%ines several metods tat elp manage treads.


The MAIN THREAD
1
Den a J010 program starts up! one tread begins running
immediately.
1
Tis is usually called te main tread o% your program!
because it is te one tat is e,ecuted (en you program
begins.
1
-t is important %or 2 reasons

EcildF tread can be spa(ned %rom te EmainF tread.

-t must be te last tread to %inis e,ecution because it


per%orms various sutdo(n actions.
1
-t is automatically created (en you program is started.
1
-t can be controlled troug T+G?0: object.
1/22/14 ANKITA R KARIA, SFIT, Mumbai 82
Some Methods under THREAD
class
1
getBame$' = "btain a tread/s name.
1
get@riority$' = "btain tread/s priority.
1
is0live = :etermine i% te tread is still running.
1
run$' = ?ntry point o% te tread.
1
sleep$' = Suspend a tread %or a period o% time.
1
start$' = Start a tread by calling its run( metod
1/22/14 ANKITA R KARIA, SFIT, Mumbai 83
CREATING YOUR OWN THREADS
1
CREATE YOUR THREAD.
1
SPECIFY HAT THREAD HAS TO DO
1
START YOUR THREAD.
1/22/14 ANKITA R KARIA, SFIT, Mumbai 84
class Mythread
extends Thread
B
C
pu0lic 4oid
run()
B
C
D!"i#!$ %&! '()! %&a% '(#$%i%u%!$
%&! #!* %&+!a).
I% 'a# 'a,, (%&!+ m!%&()$, )!',a+!
-a+iab,!$.
E$%ab,i$&!$ %&! !#%+. /(i#% "(+
%&+!a)
A thread will not
run until you tell it
to start.
CREATING YOUR OWN THREADS
1
START YOUR THREAD.
$%a+%01 m!%&() *&i'& i$ (+i2i#a,,. )!',a+!) i#
T&+!a) ',a$$ i$ +!$/(#$ib,! "(+ $%a+%i#2 %&! %&+!a).
$%a+%01 !3!'u%!$ a 'a,, %( +u#01.
M.%&+!a) %4#!* M.%&+!a)015
%.$%a+%015
1/22/14 ANKITA R KARIA, SFIT, Mumbai 86
C+!a%!$ a
#!* T&+!a)
Invokes run() method
THREAD METHODS
1
,5118H:-
Suspends e,ecution %or speci%ied period o% milliseconds. :elay
period is mentioned in milliseconds. -t migt /="%9 a#
I#/1""68/1$E!018/.%# $+appens i% some oter tread (ants to interrupt tis
sleeping tread.'
1
.,A5.v1H:-
:etermines (eter a tread as %inised.
Geturns true i% te tread upon (ic it is called is still running.
1
D%.#H:-
Tis metod (aits until te tread on (ic it is called terminates.
1
*.15$H:-
)auses currently e,ecuting tread object to temporarily pause and allo(
oter treads to e,ecute
1/22/14 ANKITA R KARIA, SFIT, Mumbai 87
:e%ault )onstructors o%
-hread 1lass

T!r"a' '"$in"s t4% s"ts %$ (%nstru(t%rs, %n" $%r (%nstru(ting a


t!r"a' %n a s"5arat" instan(" %$ Runnab#" an' t!" %t!"r $%r
(%nstru(ting a t!r"a' %n (#ass"s t!at "3t"n' T!r"a'/

T!r"a'=Runnab#" t!r';b>

T!r"a'=Runnab#" t!r';b, String t!r'Nam">

T!r"a'= >

T!r"a'=String t!r'Nam">
1/22/14 7A ANKITA R KARIA, SFIT, Mumbai
T9READ PRIORITY

?ac tread is assigned a priority! (ic a%%ects te order in


(ic it is sceduled %ro running.

Same priority treads are e,ecuted in 3)3S %asion.

@rogrammer can set is o(n priority (it %ollo(ing


command2-
TreadBame.set@riority$int Bumber'>
Te Bumber is an integer value to (ic te tread/s priority is
set.
Te -hread class de%ines several priority constants2-
MI,(PRIORI-Y 5 )
,ORM(PRIORI-Y 5 6
M04(PRIORI-Y 5 )7
;se in %ollo(ing (ay 2- Tread.B"GM<@G-"G-TH/
1/22/14 77 ANKITA R KARIA, SFIT, Mumbai
T9READ
SYNC9RONI:ATION

Syncroni.ation is te ability to control te access o% multiple treads to


sared resources. Syncroni.ation stops multitreading. Dit
syncroni.ation ! at a time only one tread (ill be able to access a
sared resource.
public syncroni.ed void Metod1 $'
K
0ppropriate metod-related code.
L
public my3unction $'
K
syncroni.ed $tis'
K
// Syncroni.ed code
L
L
1/22/14 7B ANKITA R KARIA, SFIT, Mumbai
+$i# '%;<,"

this is a re%erence variable tat re%ers to te current object.

;S0G? "3 this S?HD"G:

)an be used to re%er current class instance variable.

)an be used to invo#e current class constructor.

)an be used to invo#e current class metod.

)an be passed as an argument in te metod call.

)an be used to return current class instance


1/22/14 B0 ANKITA R KARIA, SFIT, Mumbai
!#a$%&e'
public class Point
pri!ate int "# $;
public Point(int "# int $)
this." = ";
this.$ = $;
%
%
!#a$%&e'
public class Point
pri!ate int "# $;
public Point(int "# int $)
" = ";
$ = $;
%
%
&'() *(++ ,(-. /01P(+. &(1. .2202
1/22/14 B1 ANKITA R KARIA, SFIT, Mumbai

Vous aimerez peut-être aussi