0 ratings0% found this document useful (0 votes) 57 views34 pagesInheritance, Package and Interface, Exception
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
(eed WY Year ¢seé
uniT-§ Z Upsk
Wh “is a’ Yelatiouship exisht bebweer two claeses, we ure
Imhelauce -
* The parent class is lermed super Class aud the iuhented
Oclass is Hae sub clase
* The keyword extends is uted by Hae sub class bo iubent
Ye featurer of Super class.
class Fersou Person is wnore geveralied)
. atkvibuker Qud fuuchouality of Peyton defiued */
j Shudenk it a” Person and it)
class Shidet extende Pevsou Ae speed
{
/ivboitt He atbibutes aud fuuchoualibier of Person aud in
addifiou aud its owu Specialities */
J
x A Subclass canuot access the private munbers of its
Super class.
x Tuhevitauce leads bo reusability o todd.
Juhoitaue :-
+ Mulli- level tmlentawce it allowed im Java but wot wulbiple
imlenitauce -
Grandparent | [Patemal “Matera
Parent | ; \
eats Child
cuuald
Allowed im Java Not Allowed iv Java‘Although Java is strictly pass by value, the precise effect differs between whether a primitive type or a reference
type is passed.
‘When we pass a primitive type fo a method, i is passed by value. But when we pass en object to a method, the
situation changes dramatically, because objects are passed by what is effectively cal-by-reference. Java does
ths interesting thing that’s sort of a hybrid between pass-by-value and pass-by-reference. Basically, 2 parameter
cannot be changed by the function, but the function can ask the parameter to change itself via caling some
method within it
While creating @ variable of a class type, we only create a reference to an object. Thus, when we pass this
reference to a method, the parameter that receives it will refer to the same object as that referred to by the
argument
This effectively means that objects act as if they are passed to methods by use of callby-reference,
Changes to the object inside the method do reflect in the object used as an argument.
In Java we can pass objects to methods. For example, consider the following program
1 Java program to demonstrate objects
passing to methods.
class ObjectPassDemo
{
inta,b;
ObjectPassDemofinti int}
{
azi;
bei;
}
IT return true io is equal othe invoking
IT object notice an object is passed as an
{argument to method
boolean equalTo{ObjectPassDemo 0)
(
retum (0,
}
}
Driver dass
public class Test
{
public static void main(String args)
{
CObjectPassDemo ob1 = new ObjectPassDemo(100, 22};
CObjectPassDemo 0b2 = new ObjectPassDemo(100, 2);
CObjectPassDemo ob3 = new ObjectPassDemo(-1 1);
System out printin¢obt == ob2:* + obf.equalTo(ob2));
System.outprintinobt == 03: + ob equalTo(ob3));
@
a&&ob==b);Itstrative images for the above program
Three objects ‘obt’ ,‘ob2 and ‘0b3' are created:
ObjectPassDemo obt = new ObjectPassDemo( 100, 22)
ObjectPassDemo ob? = new ObjectPassDemo( 100, 22)
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1)
Passing Objects as Parameters and Returning Objects.
From the method side, a reference of type Foo with @ name ais declared and it’ initially assigned to nul,
boolean equalTo(ObjectPassDemo 0);
Passing Objects as Parameters and Retuming Objects
'As we cal the method equalTo, the reference‘! willbe assigned to the object which is passed as an argument,
ie. ‘0' will fer to ‘0b? as following statement execute.
System out printn(‘obt == 0b2:* + obf.equalTo(0b2)};
Passing Objects as Parameters and Retuming Objects
Now as we can see, equalTo method is called on ‘ob’, and’o’ is refering to ‘cb2’, Since values of a! and ‘bare
‘same for both the references, so {condition is true, so boolean true willbe return.
ifoa==a&kob==b)
‘Again‘o' wil reassign to '0b3' asthe folowing statement execute.
System out prntin(‘obt == ob3: * + obf.equalTo(obg)};
Passing Objects as Parameters and Retuming Objects
Now as we can see, equalTo method is called on ‘ob, and‘o’is refering to ‘ob. Since values ofa! and ‘bare
‘not same for both the references, soi{condition) i false, so else block will execute and fase will be retum.
Defining a constructor that takes an objec of its class as a parameter
‘One ofthe most common uses of object parameters involves constructors. Frequently, in practice, there is need
{o construct a new object so that tis inilly the same as some existing object. To do this, either we can use
Object clone() method or define a constructor that takes an object ofits class as a parameter. The second option
illustrated in below example:
1 Java program to demonstrate one object to
I intaize another
class Box
{
double width, height, depth;
‘Notice this constructor. It takes an
‘object of type Box. This constructor use
Ione object to initalize another
Box{Box ot)
{
width = ob. width;
height = ob height;
depth = ob. depth;
}constructor used when all dimensions
II specitod
Box(double w, double h, double d)
{
width = w,
height
depth = 6;
i
‘compute and return volume
double volume)
{
retum width * height * depth:
:
Z
Iriver class
public lass Test
{
public static void main(Sting args)
{
‘creating @ box with all dimensions specified
Box mybox = new Box(10, 0, 16);
I creating @ copy of mybox
Box myclone = new Box(mybox);
double vol
get volume of mybox
vol = mybox.volume();
‘System out printin(’Volume of mybox i *+ vol);
I get volume of myclone
vol = mycione.volume()
‘System out printn(Volume of myclone is* + vol};
}
}
Output:
Volume of mybox is 3000.0
Volume of myclone is 3000.0
Returning Objects
In java, a method can retuin any type of data, including objects. For example, in the folowing program, the
inc:ByTen( ) method returns an object in which the value of a (an integer variable) is ten greater than iti in the
invoking object.
{Java program to demonstrate returning / of obje
ass ObjectRetumDemo
{
inta:
ObjectRetumDemo(inti f= is} 5| This method returns an object
ObjectRetunDemo inerByTen()
{
CObjectRReturnDemo temp =new ObjectRetumDemo(at0);
return temp:
}
?
I Diver class
Public class Test “
©
publ static void main(Sting ergs) \
{
ObjectRetumDemo obt = new ObjectRetumDemo(2);
ObjectRetumDemo ob2;
(0b2 = obf incrByTen();
‘System out printinobt.a:* + ob.2);
System.out prntn('ob2a:" +0622);
}
}
Output
obta:2
ob2a: 12
Note : When an object reference is passed to a method, the reference itself is passed by use of calLby-value
However, since the value being passed refers to an objec, the copy ofthat value wil stil refer tothe same object
that its coresponding argument does. That's why we Said that java is strictly pass-by-value.
Passing ot ‘arguments to Meth
Object references can be parameters. Call by value is used, but now the value is an object reference.
This reference can be used to access the object and possibly change it. Here Is an example program:
Program (Rectangle.java)
public class Rectangle
{
private double length;
private double width;
public Rectangle() { length=0.0; width =0.0; }
Public Rectangle(double |, double w) { _lengt
public void setLength(doublel) { length=|; }
Public void setWidth(double w) {width= w; }
Public void set(double |, double w) { length=1; width =w; }
public double getLength() { return length; }
Public double getWidth() { return width; }
Public double getArea() { return length * width; }
Public double getPerimeter() { return 2* (length + width); }
}
width =w; }
Program (PassObjectDemo.java)
pe
* This program passes an object as an argument.
* The object is modified by the receiving method.
sy)ai
public class PassObjectDemo
{
public static void main(stringf} args)
{
// Create an Rectangle object.
Rectangle rect = new Rectangle(10, 20);
// Display the object's contents.
System.out printin("Length : "+ rect-getLength());
System.out printin("Width: " + rect.getWidth();
System.out printin("Area: " + rect.getAreal);
// Pass the object to the ChangeRectangle method.
cchangeRectangle(rect);
// Display the object's contents again.
System.out printin();
System.out printin("Length : "+ rect.getLengthi));
system out printin("Width: " + rect. getWidth0);
System.out printin "Area: "+ rect.getArea());
}
i
* The following method accepts an Rectangle
* object as an argument and changes its contents.
af
public static void changeRectangle(Rectangle r)
{
r.set(30, 5);
}
}
Output :
Length : 10.0
Width: 20.0
Area: 200.0
Length : 30.0
Width: 5.0
‘Area: 150.0DYNAMIC BINDING: Crymea ne ella ws peer)
* tan we do tis?
Dotkoy obj = ue Surgeow (5 CY®
4 C fo porate)
* A veference bo a Supey class can refer f a sub clace
object.
x Now wh we Say obj-breatPatient (), which version of the
withod it Called ?
Tk calls Surgeou's version of Une breakPatient meltrod
is poinling to a Surgeou object
used bo call a method,
Hie welttod bo be invoked is devided by the JVM,
Ue reference it pointing to
yelevence bo Dotlor, it
ik poiuts bo a
as the Yeference
kT a base class yeference If
depending on the abject
Foy q, wes though oby it &
calls the mutiod of Surgeon, at
Surguow objet.
This it decided during yuu - time
oy yun-Hwe polymorphitm
aud bowed dynawic
Redefining a Super class .mettod in a Sub class
is called method OvErviding.
©(1. Surgeow \ Pocky [1 Fawily Doctor adds |
| overndes treatPahent ‘worksAlHe¢pilal One. ‘View inelaute
| imethod ies, giver r | variable.
nw deGuition bo the eee Hebemiten net
meltiod . A kK | welied |
(a Adds one new \ ; /
| nethhed ) ; Vy ieee
alien Se eee sr
ir NV [FamilyDotor
call resi | Sub mrakesWouse Calle
classes ae saeen |
ee ree | giveldvice |
make Incision) 1 a
(Gaile teal Patient
Doctor doctovObj = new Dockoy O ;
— matted of Dolor class )
doctor Obj. treat Patient (>
Ob) = 8 OO;
ington surge dal = awe Sargean On ea cig al bond
SurgeouObj. tveatPabent () ( wrthed ot Surgeon css)
Some vulet in overvidin are
The wellod Sigvature ie. metiod name, parameter list aud
yetuvn type have bo mateh cra ckly ,
The ovevvidden wellod can widen the accessibility
but wok viavvow ik, ie, if ib is private im the bare
duld cast tan wake if public but uot the
@
class, the
Vile - VersaSTATIC
Dynamic
«
Funchiow Overloading Fauchou Overviding
~ within Same clase more thaw ~ keeping the siqnatnre
ome wmettrod having Same vame aud reli type Same,
but difFeving im Siguature metiod iv the base clase
is vedefiued in the
derived clace
* Resolved dunug compilation fme. Resolved dung ran time
+ Ream type 11 wok part Which wellicd to be invoked
mitted siquahire- it decrded by Hhe object
thal! evwefeveate poli te
aud uct by Hae type of
the velerence.
ABSTRACT »
& The abstract key word cau
be used for meliod aud
class
abarack metred Siquifies if bas uo body, ouly
* Au
dculavahou of Khe wetted followed by ata tai
babar public double caleulate Area () ;
a
oy wore abshack metrode
@
P) Gh alas: hac enedeclared inside it, the class must be dedared
abstract
abstract class Shape
q
UW class definition
J
Au abstract class instaubated ie objects
created from an abshact clafs.
abstract class caw poiut to
thereby achieving
canvok be
cauvok be
Reference of au
objeeks of iks Sub- classes
yun - hue polymorplisws
Comsidty a Sttuano Where You coutidty a guacvali d
Le
class Shape whids Wat two Subdasses Civile a d Beck
ud Reka ye
Civde avd vectangle have Haeiy oun way to Bee
et
area.
8, Slape class
-ik oly provides the guideline to tte child castes
meted Should be implemented in thom.
beem declared abshatt in
cauuot detide low fo calculate the area
Hak sudr &
metlred bras
the Supey clase ie Hie method Sigualtre hat ben
provided but fhe oaleworgttation bat been Aclerred,
abthack public void
calculate Area (0;
calculate Avea O
ySiaee
[Rectangle
D)
[Civele |ky:
abstvack class Shape
abshact public void calculate Area C) ;
public void gekColor ()
Wode + color the Shape
ce
ce
Noke =
* Au abshack class way also have
metrods
% For desig purpote, a
ik does uot contain amy
covcrele (complete)
cast tan be declared abshact
ev if abstract meltiod s.
abshack - Rules bo follow
AA
CN a
k The following bevel dee marked wilh “abstract "
wmodliFity -
Vv Cousthyucters
v Stoke mithods
V Private method 8
wit * final ” od fier
marked
@
V MethodsFinal
“final " modifier tat a meaning based on ik
*
ae
usage
& for mumbo data aud local data in meltodt
= Primitives : vead- ouly (toustaut )
~ Objeckt » reference is yead ~ouly
couvenHiow
~ Ure oll upper cate Ielbert Dy tenveuicr
& For wellods: No overn dang
+ For classes : No inenitauce «
& Julwhace wan vetcue “fo
gimuar te 2 abstract clase
is that Coukains
4 Julevface U8
ouly abstvark wmiethode-
x The fuuckoualiid 4 Rey eet
xterds lass
interface.
be placed in au
4 Go class Dog vow C Auiwal aud implewnenk
Pet Hi
[Avwnal | sek
ee :
extends S TuaplunewhInteafaces tn Tava. é
All methods in an inteaface are tiplictty public
and abstract.
3% The class chich implements the inteaface needs to
provide functionality for the metheds dedored in the
Inteaface-
— A dass needs f be declared abstract f at deast
one of the metheds th the interface fs Loft undefined .
interface Pet
void beFalejndly Os
véid play;
Mass Deq extends Antmal implements Pet
public vid befiendlg -)
j U/ Functionality
ae
public void play O
77 Fanctionali ty
5
(1 other functtons @
1
J
An Fnterface can outend feo one ov mane) inkerfacos .X An interface may define dato twembeas and these axe
implictty public, final and static.
# An interface cannot have paivate or piotected
members °
X% An thterface can extend ently one class but
implement any number of interfams .
class Peasen oxtends Living Bewng “urnplemnents Employee , Fuend
Interface RtcableAritmal eatends Aiiumal » Vehidhe «
# An interface cannet be fnstantated.
® An InteaPa.ce veference can pornt bo objects of its
Implementing classes .
THE same Interface can be implemented by classos
trom — different fphelikanay any
Pe:
-Poxot' a ' Bid but also a fet
~ class Paeot catends Bid tmplenert Pet § 3
p hitevface Pek is being used by both Deg and Rot.
XAn jnner class ts a dass defined cwfthtn another
class -
Mt cAn toner class is a nen- static nested class . thas
access to all ef the variables and metheds of hs outer
class. §9)#* An inner class & fully evithin the scope of Hs
enclosing class -
SEANONY MOUS INNER CLASSES :
An Anonymous Taner class ts a class that ts not
assigned any name -
class Outer
int ouber-1=100 +
wid teste)
{
Taner “inner =hotw TrnerO;
Innes . olisplay 0 +
Y this ts an inner class
03s Tnner
5 void display oO
systern cet. paint ("display + outer1 =" rottkey—x) ;
(9)——
dass Tnner Class Dero
5 :
public static void mato (sting Oe ))
;
Outer ext. =now Cub O
‘ euler. test 0) ;
5
Packages in Java ldhy > idhak)
# Reusability of code is one of the mest Impoxtant
Aequirements in the 5 efteoare thdus
te Ressob hy saves time, effert and .also enswres
consis
ia dose once developed can be roused by any
PRL eae wishing te incorporate the class
th that —— a gem
of Paci
oe dava, the code which can be xoused by other
progtams ls put into a * Package’.
¥A Package is a collection 4 classes, intorfaces
and /@ other
es .
{7# Packages are essentially a means 4 oaganiing
classes tegethior as gheups
Featuros 6 _ Packages :
xo yoo classes “nto smaller ures and make
t easy to Jomte and use the appopratte class
file :
X Avoid sraming conplicts
~ Package names can he used to identify fou
classes -
¥ Packages allao you protect vyoess classes , data
and methods a a darges coay than on a class - to-clas
baste «
Caenting a Package :
gn Java Packages aw created tn the fellewtng
manne :
package package—name ;
my package
v) class Calailater is inside the
Th
1gpackage wpe.
public class Calculater
5 public tnt add (int »,inty)
votuan (x+y) ;
4
Drnporting a Package
ftiow can a class which fs not a part af @ package
vouse the dcagses ch the package /
—use this class as Zpocknge-rame> « Z class_name >
Speen to a class always bg ats poll
quali.pied name becomes cumbersome -
¥ dn ava, the Packages ean be imported! into a
program th the following manner :
— import 2 package —name > . Z class—name? 3
# Suppose we ws fo use a class say My —class whase
location ts as follows. Hee
[rapachage — (egsutpacage —raclass
— import mypackage « rnystekpackage - Mydass 5
(9¥ Two lays to tinpoat a package
¥ ctmaporting a specific Package Member
—impert mypackage « lalate ;
* Trapoating an Entie Package
- trapoxt: my package #5
BEST PpRCTICE:
+ mport enty those classes that are aeguised
th yoo code, alo not Import the entise package «
idhat about namihg conflicts df too Grapexted
packages both have a class with tho same. name)
—Needs fo be xcselved susirg sfelly quedificd name
Class Path Setting
ple. and TVM must Lknow whee to gird the
+ dass file -
— kdhen cwosking with packages - classpath setting
chas to be one [evel ap the package hiz-rarchy ;A java exteplow is au objeck that desenbes ay
cxcephowal /evvor coudihiow that lias ocuryed in a pie
ce
of ode at “yun bme
wee
Excertlon:-
| excephi coudih a t
| When au excephoval eh on arises, Au objelt
| vepreseubug that excepHiow tH creaked aud Hnrowu im
the weltiod Urak caused bot evvoy.
REPRESENTATION OF PROGRAM EXECUTION.
DIAGRAMMATLL
[Tova ede] classes zip: classes ueeded ab run-hme
_ by java inkerpreber et
(Bava Covapile” teephion | Classes
\ Javae | 7 Tava
x Vs Tafrcede Java Juterprebey : java |
Ne ee cata
[Etvov oy Extephou fae
Exuphion Type Prog vam
dikerwiued [_Exeouiow
class created
Related message
displayed
be guaevated by:
[object of Excephow |
| Exceptions cou
Java Yun- Hwe Syste
ERROR Q)Genevated by the wde:-
EXCEPTION
THROWABLE :-
SS
* All &xcephiows fupa ave subclasser of tre builé-in claey
THROWABLE
+ Turownece it at the bop of the Exception Clast
Hierarchy,
Exception ‘Tyres:
THROWABLE
= Evroy )
w) -
Excepho
ond
Rhack over low
[Avvay Ot Tudor Out OF
Bounds
ONCAU GUT EXCEPTIONS :-
class Uncoughtex ¢ ;
public skalic void maiw (Souq aygs [3)
\ut do;
inka = 42/0;
4
4 ye| Output
Java.laug. ArithaehcExcephou : / by zero at ExcO-main( Uncaughtex.
java:4)
Tava oxcephiow - haudliug
x by
# catele
» Urvow
+ Crows
+ Finally
E
Exception - HANDLING:
& Progyau gtatumurh bo be monitored for excephous are
coutaimed witin by blouk.
# Your ede caw cata thir excephow using cater aud
thaudle ik im Some vakoual waver.
poe
# Use the Keyword Urrow bo Ure au excephon
# Auy excephow Haat 6 Urvown out of a method
Urows Clautt
wae
¥* Auy code tat absolutely wust be cxceuted is put in a
Finally block .
| (29)|
| clase Haudled Excephow
' public stahe void main ( Shimg args FD
a
it d,a3
by ¢
dzo;
a=4a/ds
J cake CAritamthe Exception ot Sy thw. out.prinktin ("Division
by 0"; 4
:
di
Output.
Diviviow by 0.
&Adwantags of Aandting excip
tions :
Ost allows the pregrammn to fic the vor.
Ivuninating.
vy-calh Control Fleur
i]
sce. gen Bee-Mautiple catch. hawses_
© Ore Mock Ff code camses multiple Caxystien,
@ Jue 6 mere calc clauses,
ote a me A oy 8
@Unwachable ode.
age Ahalic wil madn (dung agscy
i
int a= Lengthy
ind b= a,
dirk CC1= 4195 C[42]=4949;
J oabch Catithoulc Exception €) £ dyslim.eut. prcitt
(Qivide by a" se)sh
colic Carma Sno Out bounds Cxveptien e)
E dystom.eut, print Wony Andia 606: "+e);$
uystirn out priinttn Csfften Huy tatch Ibock.")s
of
[Nested truy Atatunents
OA Iny and its colch san Je rusted inside the Mock
of anetiur Juy.
OSL ecocutes wurtit one Af the Lalch. slatuments succeeds
WL Tawa sunfire. aystum Jandts the exception.
@fe public class Nested Tou
tT public static veld main labuing axgst1)
coe
bs a
dt cOI> £45, c640]= 99 ;
ae Indu Out boundabe. )
ae pies et as pen ¢
ee focceplion 0) 13
j
J See ad
Define t
® cuales a Mteck of cade that wih Ae
em eg Cn mee ei ea thvown],
a
dnt Clrum4 = £12, 6, 10, 8, -L.645
fink [J numa =f 1,5, 35,20, 1189s
public * hs veld rain (un angst)
i sr Finally Some 0;
foi numt);
jasodNara (frst
a joadNunes Circ C7 arnay)
f nt Count <0, hast= 0}
by
t i g , Y
fo eeflow. ze-l)
nw 5
ti
a
t dyslen. ous print Cast “+ last)
§
4
5
Inu, catch lotrel de
cools veforw Fry
ea Caception occurs
By Neb caich eck
"Fiably block (if Hani)
ee LC
[ code after ty)
—~
va
Ww| TRE Tron! Creuse
* Thacuo an oxcoption oxplicity -
thxoeo Threcoatble Instance
le
K using a porarmeter ‘into a cath clarise
€ Sth HP atet.
Caeateng ene with the nee Oper
ckiss Thxovoderno
State void cdemepioc OF
tay § throto neco
Nutlpointerxcophén (“dlen") ; 3
catch (Null Pinter Fucoption €) §
System. out. prerttn (" demnoproc:");
three € 53
//outpet + demopioc
publte static void matn Ctaingargst)
Stay Fdernopio cc); 9 -
catch Chet! PointeaEaceeption e)
§ System. cut. patntln ct Recaught "4e), 4
4
Ws Recowig ht Java. fang - NatlPointerEaccphén demo
as ane metopc | METHOD >
g \ |
he Aue : pox | tCcend) §
| i ha
| ‘hatch Eaeopibn 4 dapat ot Excopticnd);
cufputspeintinCAN);) Capt -prontln ("2");
|Cull Sequence
Method A ———> method B-—>Mefhed ¢ — Method .
aaichor perpagater pepaga
Stack hace
) Je
— |6)—>}5\ SI
A| NAA [RY
REY
le
¢ én that Is not
i fo thieed a Fxcophon
Cai eos ee aces ‘
shandled -
: . thea subclasses don't
Bao and Rinkineeption ary q
= Type, methed— name ¢ posametea -list) tixcwws excephn -Itst
5 bedy of methed 5
dass Throwsdemo §
Static void theceoPioc 0) Throws
MlegabAccessExcopten 5
‘threeo het
‘thegat Access Fxcoptién C'demo");
5
Plblic stectis void main Ching ange ey) §
tay f thiewPoe OF j
catch CH
j
cla
legal Access Excoptin eng
Systers weet + pxintlh Ch Guight 46) 744Tyats_ pull _Euophons (pve defind Gicecglen).
* Towa Aehines several orcoption classes inside the
standard — paca. java. lan
poe
A
oa Ener
RuntimeEncopkion
Unchecked Fxcopfih = Runtime Excopttons /ERROR
Saamplo: ‘
* Numberoimaticacoptten
* dllegalA xqument Excephen
me Sut Of Memoay Faas
Checked Fa coptons i
chetkod Excoption = checked at aornpile terne
X these ever cue duo extenal ciraumstanas that fhe
pegiateme ceenret prevent «
Exs J0Eacephton
| Sa\a!s Buitk to FacoptOng - .
Te Following M2 Java's Checked Exeephens
| * classNot Found Fxcophton
* dlone Not: Suppoatedl Excephion
% legal Access Fxcoption
% Fnstantiation Excopton
% thheupledl Eeephicn
% NoStich FieH Excoptton
% NoStehMethed Exception