0 ratings 0% found this document useful (0 votes) 4 views 72 pages Java Unit 1 Part 2
The document provides an overview of inheritance in Java, explaining the concept of deriving new classes from existing ones, where the old class is termed as superclass and the new class as subclass. It outlines the benefits of inheritance, such as code reusability and sharing, and categorizes inheritance into types including single, multilevel, hierarchical, multiple, and hybrid inheritance. Additionally, it discusses access modifiers and constructors, emphasizing their roles in class design and object initialization.
AI-enhanced title and description
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
Carousel Previous Carousel Next
Save Java unit 1 part 2 For Later Unut 1
Inheritance
*Kkx*
Inheritance concept:Inherirance Concept
Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and ne}
class is known as subelass. The subclass inherits all of its instances variables and methods defined by t
superclass and it also adds its own unique elements, Thus we can say that subclass are specialized versio
ofsuperclass,
Def: Creating a new class from already existing
Benefits of Java’s Inheritance class is called inheritance
1, Reusability of code
2. Code Sharing
3. Contisency in nsing an interfaceThe process of deriving a new class from already existing class is known as inheritance.
* In OOP'S the concept of inheritance provides reusability, this means we can add
additional features to an existing class without modifying it.
* The old class or existing class is known as base/parent/super class. 2 ( / ( \
* The new class is called child/derived/sub class. a ZA
Types of Inheritance : Inheritance is classified in to the following forms.
Tt STS
1. “Single Inheritance.
3. Multilevel Inheritance. 4.” Hierarchical Inheritance.
5. Hybrid Inheritance.1.Single Inheritance:fF ; ie Base Class
. | a | Derived Class- / dhe Sporto narne |
i ~~
j a le
Subdan e% SP ‘|
boa
Ny
Wty)F programe:
I mpet yaya Lavy x;
Class One
i
Inb es
Yoid gta
A zl00;
So plac" x Value =" $22;
3
}
Class Too exlendly one
Int y, total:
Void actyc)
=o;
Sap ("9 all
Single Inheritance
Void Som
t tol = atI,
$0 ple Cl pAddiie.="+ PHY,
\3
\clags 7
be v m CShing aresli)
Tao by = KOO fwocd,
| oby gsxr:
J by gehyeo:
ob) Sun,2. Multilevel inheritance:* Multilevel Inheritance : The process of deriving a new class from already derived
Ale LN Aa
class is known as multilevel inheritance.
Base Class
Derived Class
Derived Classprogram: Mel
Irae jee lang. 5
loss Sup
Int xX 5
void gto?
x= 1007 i
S-o-ple Cla values" +705
t
5
Class Sab extends Sup
t mgs
Void GeO)
= 2005
° ‘ PC "values" + y):
Tnherstance
Ke “Subs extends Soi
tot;
Void added
£ tel = Ate
Soph (" tee = b+ tet Dy
Int
NP
J x |
class ME |
|
tg. vem Steg args I)
c Sub) 3
Sub, obs Kew Subr0d:
Ob}. te >
a Vue; Gab
7 oby- add CD; ok: es
)
} ] “t [Moo 1
[log gen )
ae seed J BS get
oa = (00 /
Laka we3. Hierarchical inheritance:* Hierarchical Inheritance : The process of deriving more than one derived class from
only base class is called Aierarchical inheritance.
f
t
}, Hierorclicnf Inhearctoance
g 4
Sapa hon,
cess ~ Spucton
y = Sub | Ea
. Coss Sab) extends Spr tor
{
ih
an Saba exdoncds x chee
}
ad
£
I)programe: = Hierxarclice{ Inheritance
(mprr jos ; Leng x, ass Sabo extenc S4P
Class Sop \ Int S53
' id MinwoDd
Iinmt x, oO Y vc a ZH
Void gekayo sfacy; [sabe]
t R=loo, | Soplnc" Mines =" 465° y a) \
5 = 50) | 3 /
5 3 > obj,
j class Hi os
Closs Sub, extends Sap PS.v. AC Shang aryse yY [seas
= — _ 7 5 Som GB oat
ImF Som + Suby ok) = he see : -
Noid add “) Subr2 ob2 = vena) M4BICD | 5 hyo
bry. aed aged, \™
Sums x+y) Obs ys 9279
' 4 aby GURYO |
So PaC Addition =" + Som); a eta,
} Ob) 2- Minuscd &
3 3 a
we4. Multiple Inheritance:"© Multiple Inheritance : The process of deriving a new class from more than one bag
ii AD ee
—
class.
—————
Base ClassSy ntax:
/ Multple Teri tance
Tn beh face
i
WI
Sub
ji)
SeoPpr
Sup 2
ton plments
sake gate
( Pp Cop,
ee xr~zle
Sepy , Lop eeL Msp Trhesi fance
pw y aR Lg my = .
interface Sop Ko pe
y ; pole Ana Link A= lo, E-pd [snl
| pabhe abstract wid gree
| j
fntafre Sop
ubke inl int jar
pric abstract void gry O-
J
Class
vad Som) ate
onc paditios =" + (449) )5
| :
Class cub anplerments Sup) » Se Ck ae
~ \
\|class mi RE
void quae) | : '
' ; ting argtl J % fe
fog pln" Value + %): aw m (thing ogi J)
“cub obj = Kew) SabO>5—/
Void ge Sr que, Sc
t 1 "l & aco: 9°
i buple Cy Vala +29, } oes Me neay
35 Hybrid inheritance:* Hybrid Inheritance : The process of deriving a new class involve in more than one
form of+ jtance is called hybrid inheritance.
poe ee nee cny
Single
Inheritance
~-----
'
‘
'
t
'
'
'
'
'
'
1
’
'
‘
‘
‘
'
4
were eee 5-- ee
Multiple
Inheritance
Y
Bee ee a ee ee en et* Hybid Snhewlanee +
Hypid Inheslawa it We combination ob bola Single
and Multiple Iuhenlawce» It is nd divedly Suppotad in java
ovly thrngh tbivfacet we can achieve this
a
I
Nolet
A clase member Wat has been daclavad ag privale will
vemain Pavale te ts class. TE is net accessible by oy code
vutede it: class, eludivg cubclascos.Examples t-
¥ Single Inhevilance frample
class A
{
voick déepN)
f :
a class A 5
System cout pri alla decp method
i
clase B extends A
t
void displ?
U' dsp aetnod oh class BD
system seul paella
public static void main (SM4g avgst 3)
{
Bw behew BO;
oh clots A
sep ner caethed
dak clos &
foe dispAOs Healt co
ria disp BU; coll dar Be
§ coukpl t+ qovee 6. Jere
jova &
disp wathod a class A
matted cf clots 6
y melbs
diyx mall level Duhevilance Examole.
class A
{
void disp C>
{
gysttn souks pinkln (dich watfad de clatt A‘):
i
class RB evlands A
£
P.
Scanned by ¢
Noid disp)
t
cystew-cuks prindla Cdesp method ob class BY;
q
I
Class cC evlends B
£
void despCe>
souk. pvintn U" des p methad of clevs cy
System
q
public Stakte void main (shang avg)
{
Co cznew CO;
ce disphOd3 Meal dir AO tb clas A
ee desp@crs Meatl dise8O oh close
ce disp C095 Meoll drepce? oh Clas €
i ! utp: gavae C-Jova
eva ¢
disp method & claw A
disp mellud ak class B
disp method eh clu |Hevorehical Snhewilance Example.
class A
i
public void ispAc)
“ye
* shen cate pa disp method & class A‘)
1
} "
class extends Ai Fs ge en
f 1
public void tespRt>
8 yale wouk- prinkla C ep welhed a class B'S
7?
Pre
Scanned by Cam
class C enlaudys A
{
public void dtspce?
Syitang cout pantle Ccletp motted ob clots ¢°)5
4
}
close D enlands A
t
public void dapoO
system sok prinkle c
j
f
class HIwheuilance
t
public slatte void main (Shaw avgst])
{
B be new BO;
b. disp BO,
be desp ACD;
t ”
disp method eb clos DB"):
C ce new CO)
c.dicp CO,
ce. dicpady;
D denew DO;
ds desppor,
d-cltspAly,
i
3 outpal- qovoc HSukevilant - Java
qeva tinhe wlowce.
disp meted of clatr B
. dip wadhed chee A
I vdcsp methed cb chic
disp melted ok clase A
dice method ok close D
drip melhed ob clo“ AMember Access:% Access Modifiers (of) Membey access Tuk in gave. s-
specifies aece ssibilily (seepe)
The access med-fers in Java
ck a data mambev, melliod, conttucly oY classe
Theve ave Ulgpes A access modifier Mm Save
1. prvalé
2. default
2. protected
4. public
\s_privalé
ble oly Within clots.
The privala access modifier is accessi
Example:
class A
{
privale ink dala = 40;
privale void sgt)
{
system out: print U Hello Java");
I
?
public closs Simple
t
public Sladie Void main (sting ovgita)
{
A okj= Mew ALY
Syctem souk. ponthc hj: dake):
obj. mtg 005 output Jovee Seple Tova
} Compile Time Evo
i compile Time Evrar
Tn The obeve example , kle hove crated woo Classes “A and Simple.
Clos: ‘A’ coWlains privale dala member avd private mallind. mle ave
accessing Iete private mewbevs ftom outside te clase,So theve
ic compile Ome error,2. defaulki-
Ty yo
default, The dafartl modicfen it accastible
don't use any mobefer, it it Feated as defautk by
avly Within pacttage:
Exorple
+ Gnthis enampe, Mehave ¢
W Sove. by
paexage pacnls wo packages pact! aud pack 24]
rad feel He ave accessing the Adef class
void mgd trom culude il’s paccoye » £0 it]
cnn be postiable ‘te acco
dom subside the pacteage wlith
dufaullk accets waders
t
Syslim souk. pinky (* Hetle”).”
3
4
I Seve by Belef javo
Package pack »
import pack. %}
Class Bde
table slate void main (Shing avgsca)
t
Ade} obj= new AdefOrs compile Tene Eval
obje rasgh>; Compile Trese Evrel
i eotyl: Jovac Belef+jove
Compile Time E700.
class Ade {
void MG O$ System oub. prnth Helle"); F
I
clas gdetd
public Stabte void main (Sing aygs 63)
f
Adel oly = new Ada;
Obj. isqer;
1 eulp ever Gdet dove
i qova Reh
Hello.
Scanned by CamScanneruy. pebble t
‘The public accets modifier is accessible everytlheve « Th
hos tke wides Scope smeny all offiey modifiers.
Example s-
Package pack ;
public class x Hoon by Kedeve
{
public void mgt)
Hetlo’),”
{ .
System ouk- printla
4
package — Mypotk;
import pat «7 Ise by Yo
clos y
t
public slakte void main (Shing avgslJ)
t \
x objs mew XC
oby« IG); pull: govoc -d + X-deve
3 toy qevor -d * Y- dove
j b yevaaymuke ¥
Udlo
Let's ‘underslanol Th. cess mod:fvers -by single table
Access Within Wilkin, oukti
— fle et ea Set al cob pactoe|
Defaull y .y
profecteat y y ~ 7
public y v ad
Y
asl y- yes, =o.
Scanned by CamScannerConstructors:Constructors
* Constructor is a special type of method that is used to initialize the object.
* Constructor is invoked at the time of object creation, It constructs the values i.e. provides data
for the object that is why it is known as constructor.
Rules for creating Constructor
‘There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of Constructors
There are two types of constructors:
1. default constructor (no-arg constructor)
114
a
Java Programming | 115
2. parameterized constructor
Types of Constructor
1) defaultconstructor 2) parameterized constructorConsteater
Reales
O) Same as ats rane
Q) No azetrntype
@ Automabkey CalledDinan Constradet
iM\eobe
Impet jave Lang x des 10 1
class Robo P 6éoVv manCShG args 1)
t é
InP x» ag? tote 5 \ Robo ob) = hw Raboc> 3
| SS ,
Roloc > //cCorsputo” ob) SumOD 5 Corsten
t
% = \00, 3
Y = 200; 3
} .
Void Som cy method ob)
é H [eS fu
fot a *4Y; keg bey Bs
So ply ("Sum= "4 Toto);
seemcanst es | =eTiewt gut chao [jut eb Constr
+ Default constructor
+ pavamelén ned conthudér
* Bafoubk concludd t=
A conthuder thak Move Me? pavamnl” is lenaan of
defatt Conshudiv » ceuat B provical daoutt vodues 5
on oljek
Exaenplt !-
clacs DefaultConsl>
t
Defaultcouly oo Contianctar method
50/60
{
system souks printha C Default Conshuilay rated called J
t
public slakic void rnain (Stang vgs)
{
Defoulk Contr dex new DefoullConsh 7
j audpul* yovae DefeulkConsle- Jove
i Jove Defoullcons
pelovlt Conctuilor wnethodl called +Defounlt Constructor
Rules [ Contax
O Came ab Claiinarce
i
s No redo type.
templet caAlU 9 =
Hy,_ - a _
- AS tubo Ey il
1 Default constructor: Des foul £ Const tucter
Tmpesh java lang * eines De |
} os Robe \p Soy AC ohng ert)
wn , b, tote 5 \f |
Into oa , \pabe ob} = =nNeo i |
Rober 2 if Defoe ey | ob) Gummo),
A=zlo; y
b=20;
3
Void Sumcy
{
i
tetaloath; ta bo ae
Sophcteme" td, 8 Bo)
: j
} | . Ses |+ paromeliviaed cons leudéy s-
9 A pova melavized contador 6 a conskudoy, thak has
poromelivs. (ov) A contactor thak have pavamelevt iy Known
ot pavameleri Xaol conthuuty +
> This isuiad fo provide deHevent volues te The
distind object.
pyaenple So
gn The ebllosing —enample , ble na
gfubuli Coss Mak hava hoo pavomeleve.
ce eymalad the conthucley ob
Scanned by CamSca
ss slodauls
(
ink ids
Stang name;
Shadowli Cink 1, sing 9) Il povowtelivited Coo
{
id=
Name =
f
void despa 6) 1/ Me hod
[
System souk-pantls C tha‘ "+name)?
I
public stadie” vod main ( Shug avgstt)
{
huslov
Shida siz new Slidewls (501, "mocthe");
Stideuli = new sladewk (sir,“ Hew!)
Sle disploy er;
$2. + despley ors
] outpuls> fava gladewli -jeve
jova students
S21 Modhy
cn Hew2 parameterized constructor: | - tags Moke
a Rebo apd yom (Shr ouwrggc 3 )
Int % Z \o : Baise ob}, = nec “Robatio’s,
ue ms 4S] p<. Robo aby = neo Rabon C9): |
haa * a axe? = neo Roboo
} iy sd plen sag
2 “SAS oO
Void displayc) a ge |
f 2) |
S.o-pla "y=" +2); 4 x
pone
1 apo) | Aga.Difference between constructor and method
Constructor
Method
ialize the state of an
(Constructor is used to
object.
[Method is used to expose behaviour of an object.
pPonseuer must not have return type.
[rested ‘must have return type.
[Constructor is invoked implicitly.
‘Method is invoked explicitly,
‘java compiler provides a default constructor
if you dont have any constructor.
[Method is not provided by compiler in any case.
[Constructor name must he sime as the class
Method name may or may not he sam
fname.
name,Creating Multilevel Hierarchy:1. Creating Multilevel Hierarchy
Create multilevel hierarchy
Itis nothing but the enhancement of the Simple Inheritance. From the type name it is pretty much clear
that Inheritance is done at ‘n” numnber of levels, witere 121.
In simple inheritance, a subclass or derived class derives the properties from its parent class} but in
multilevel inheritance, 2 subclass is derived from a derived class. One class inherits the only single chiss.
‘Therefore, in multilevel inheritance, every time ladder increases by one. The lowermost class will have
the properties of all the superclass.
[crassa]
[css]
[cece 5]Super Uses:1 Super Uses
super keyword in java
The super keyword in java is a reference variable which is used to refer immediate parent class object.
‘Whenever you create the instance of subclass, an instance of parent class is‘ereated implicitly which is
referred by super reference variable
Usage of java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent elass method.
3. super() can be used to invoke immediate parent class constructor.
The use of super keyword
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent clas
Itis used if parent class and
child class have same fields.
2) super can be used to invoke parent class method
‘The super keyword can also be used to invoke parent class method, It should be used if subclass contains
the same method as parent class. In other words, it is used if method is overridden,Super : im
Import jove- lang. *>
CUess me Supa class class Robe
é int 2S / P é
OneCimr a) ps m (Shing acd)
AHAl é
5 aie aby = new TH ¢(10,/20);
3 \ obj. splay O-
Class Tuo extends One || SobClon 5
Into og; j
Two Cimt a, int 6) 7
Super a) 5
. 2 4
3 J=P: th a)
Voted display ©) Vaid deeply
C Sorpln( X49): |Using Final with Inheritance:1. Using Final with Inheritance
The final keyword in java is used to restrict the user. The java final keyword can be used in many conte:
Final can be:
© xatiable final is a keyword it cannot be change once created
«= method
* class
ifa variable is made as final it cannot change its value
ifa method is made as final it cannot override it.
Ifa class is made as final it cannot be extended by another class
Program to demonstrate using final with inheritance
final class A
}
Class Bextends A //error since A is final we can’t inherit
{
void display()
{
System.out.printIn("demo on final");
}
public static void main(String args{]){
Bobj=new BQ);
Obj.display();
)
}Polymorphism-ad hoc polymorphism :
kKJava Programming | 164
ib Forearm hoc polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
“morphs" means forms. So polymorphism means many forms.
‘There are two types of polymorphism in Java:
1, Compile-time polymorphism or Ad hoc polymorphism
2. Runtime polymorphism. Or Pure polymorphism
Polymorphism
Polymorphism
{Dynamic or Late Binding)
‘We can perform polymorphism in java by method overloading and method overriding.
If you overload a static method in Java, it is the example of compile time polymorphism.
164,
folymor phase
_polymerphism fi eat " Py 7
re as duns ocia “f Pay 1, 7 merphs”, talich means many forms.
oa meplism 04 The ability of a messege th be dispbyed fo moran one
I Static or compile Hime pelymarphitm i= re iy achieved prigvammatically by Function ovetleacling or
i s, ism 3-. ae Ver (oacli ws
A. dynamic or Runtime pelymevphicm sa ty achieved Programmatically by function aiiasileng ”
aloual she Ke Some dats wsiling T CVirbual Function)
Function ovarleacing s- within The oe wilting Two or move Cunck, At Sam a .
oe oventescind digest ignatiret. Cytoug, Pornmetere, prunes anenias’ ea
ator Overloading '— the abil; Ty provide ‘The epevaters wilh a Special Meani sy abd
ones eG is a as Ppevaler overloading. r "gfe a aefitype, thes
Function ovatiding t - function overriding occurs tuhon a Derived cless het a definition for
tenor cae 7B i, Gate clas. Tah, ne datt function it ald be. wshidden, ome ye
he Can have The fame function ™ the base dase of welled its Derive! clatses.
Viral Fanchion {= A Virus Function iy membu finction that it dedared within a bate class and %
Ye-defined by a devived dass:1. Compile-time polymorphism or Ad hoc polymorphism:
Ad hoc polymorphism is also known as function overloading or operator overloading because a
polymorphic function can represent a number of unique and potentially different implementations
depending on the type of argument it is applied to,
‘The term ad hoc in this context is not intended to be pejorative; it refers simply to the fact that this type
of polymorphism is not a fundamental feature of the type system,
i)operator overloading:
Java also provide option to overload operators. For example, we can make the operator (‘+') for string
class to concatenate two strings. We know that this is the addition operator whose task is to add two
operands, So a single operator “+" when placed between integer operands, adds them and when placed
between string operands, coneatenates them.
In java, Only “+” operator can be overloaded:
Example on Operator overloading
// Java program for Operator overloading
class Operatoroverloading {
void operator(String strl, String str2)
{
String s = strl + str2;
‘Systemout.printin("Concatinated String - "+ s);
}
Void operator(int a, int b)
{
inte = a+b;
System.out.printin("Sum =" + ¢);
}
J
class Main {
public static void main(String{] args)
{
Operatoroverloading obj = new Operatoroverloading ();
obj operator(2, 3);
obj operator("CMR", "EC");Neen
Java Programming | 166
Output:
Sum=5
Concatinated String -CMREC
ii)Method Overloading:
When there are multiple functions with same name but different parameters then these functions are said
to be overloaded. Functions can be overloaded by change in number of arguments or/and, change in type
of arguments. Overloaded methods are generally used when they conceptually execute the same task but
with a slightly different set of parameters.
Example on method overloading
lass MultiplyFun (
1 Method with 2 parameter
static int Multiply(int a, int b)
{
return a * b
1
11 Method with 3 parameter
static int Multiply(int a, int bint c)
{
return a * b?¢;
}
11 Method with the same name but 2 double parameter
static double Multiply(double a, double b)
t
return a * b;
d
}
class Main (
public static void main(String!| args)
(
System. out.printin( MultiplyFun Multiply(2. 4));
System.out printIn(MultiplyFun Multiply(2, 4,2));
System.out.printIn( MultiplyFun Multiply(5.5, 6.3
166Java Programming | 167
Output:
8
16
34.65
Note:
we overload static methods
we cannot overload methods that differ only by static keyword
we overload main() in Java
2, Runtime polymorphism. Or Pure polymorphism.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time,
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable,
Let’ first understand the upcasting before Runtime Polymorphism.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upeasting.
SIale=y
variable of Object of
Feel ea (1s) Child class
For example:
lass A}
167Java Programming | 168
class B extends A{ }
Aasnew BOyhupcasting .
Example of Java Runtime Polymorphism
In this example, we are creating two classes A and B. B class extends A class and overrides its
display (method. We are calling the display (by the reference variable of Parent class. Since it refers (o
the subclass object and subclass method overrides the Parent class method, the subclass method is
invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
class A
{
void display ()
{
System out printin(" A class display ");
}
J
class B extends A
{
wid display 0
{
System.out printin(” B class display
}
public static void main(String args{])
{
A obj = new BO://upcasting
obj. display ();
J
Output:
B class display
‘© Less memory space
168 |in
}
Method OVAloacing -
em long 20 = 7 ae ne
a ; 5 (3)
& ex for compiletime poly or static binding P O.u mS bing args 3)
ee aad Ch ar ©) \ ob) = nur Meld)
S: o pln ("som =" + (ath); ob} add (10/28) 5
| ob) - adh (20-10, 39-3?)-
via add Cnt x, ink 9, int 3) \ ob} aad (10%, 13):
Ss. o-pha(" Sum e"4Catytd))5 |
Void add CFleot x, Flood 4) | F
© 5 op ("sum=' + (x44):
} method overloading: with in the same class writin two or more
methods with same name but diferent
signature or parametersMelhed Oversadand ta Java.
er ° °
Oviriding UA Mechanism redefining. te funchonaltly 4 Spades Metked
i. Cor) Go the Subclass.
y Waiting Tue of mere melieds ‘to Supt ond Sub classed, Such tl tke Melts have
Same name and Same Signahites, & Called — 'Melked oversling',
> Subdless Methods overtider Supa dass tnectheeu. ‘
> Dymanie palymephicen ov (ate Rimding
ex for late binding or dynamic binding or run time polymorphism
gets Supecclass
Yotd bec
So pln Ct Het");
3
\ Ces Subilis extend Superday
\
| jis mbew
S$. 0. ping" Fy"):
\ VgNeed Ovescang im Javea
aa
—_—
tmpevt jes lang KS
oss Sup class Mo
{ :
$inal yet ibe? PS. ve moan Shing argscd?
Seo plac" Hat"): t
, c Sub obj a new Sebo.
' j -
Has cub enlenda Sup obj. reboc):
Yofd wboc) 3
S.0- pin ¢c" Bye");
3
3Method Overriding :Melhed Oversadand Tm Java
——. —
Qvariding % a Mechanism redefining the functionality 4 Spades metked
Cor) Go tke Subclass.
y Wilting Tue er mere melieds to Supt ond Sub classed, Such teh tke Melts have
Same name and Same Signahses, & Called —'Melked oversling',
> Subdless Methods overtider Supa dass tnecthesu.
> Dymanic polymerplicen oY (Ake Rimding
ges S Sup eecless
Yotd boc)
S. opin cc’ Het");
3
Class = Subelss extomd Suprdean
\ {
\ \ fia thew
} Ss 0- pln" £ye");
\ nyNeed Ovescang im Javea
aa
—_—
tmpevt jes lang KS
oss Sup class Mo
{ :
$inal yet ibe? PS. ve moan Shing argscd?
Seo plac" Hat"): t
, c Sub obj a new Sebo.
' j -
Has cub enlenda Sup obj. reboc):
Yofd wboc) 3
S.0- pin ¢c" Bye");
3
3Difference between Static & Dynamic Polymorphism
Static Polymorphism
Compile time polymorphism or static
1 | polymorphism relates to method
overloading.
Dynamic Polymorphism
Run time polymorphism or dynamic polymorphism or
dynamic binding relates to method overriding.
Difference between Method overloading and Method overriding
Method overloading
Method overriding
1 | When a class have same method
name with different argument,
than it is called method
overloading.
Method overriding - Method of superclass is overridden in
subclass to provide more specific implementation.
2 | Method overloading is generally
done in same class but can also
be done in SubClass
Method overriding is always done in subClass in java.
3 | Both Static and instance method
can be overloaded in java.
Only instance methods can be overridden in java.
Static methods can’t be overridden in java.
4 | Main method can also be
overloaded in java
Main method can’t be overridden in java, because main is
static method and static methods can’t be overridden in java (as
mentioned in above point)
5 | private methods can be
overloaded in java.
private methods can’t be overridden in java, because private
methods are not inherited in subClass in java.
6 | final methods can be overloaded
in java,
final methods can’t be overridden in java, because final
methods are not inherited in subClass in java.
7 | Call to overloaded method is
bonded at compile time in java.
Call to overridden method is bonded at runtime in java.
8 | Method overloading concept is
also known as compile time
polymorphism or ad hoc
Method overriding concept is also known as runtime time
polymorphism or pure polymorphism or Dynamic binding
in java.Abstract Classes:1. Abstract Classes
Abstract class in Java
Acclass that is declared with abstract keyword, is known as abstract class in java.
© It can have abstract and non-abstract methods (method with body).
© It needs to be extended and its method implemented,
It cannot be instantiated.
Example abstract class
abstract class A.
{
}
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
boady or code
Example abstract method
abstract void printStatus()//no body and abstract% Abstr class:
Abskradion i a procots ch hiding the
aud shawing only dancldualily to the Uses
In amolber wy, it Shows only important
aud hides the iwlérnal tars PA, example send
auth bpe tie text ond Senck the message « Jat dlow't
tke etiege delivery
deat Keyword,
inde menation debils
thieg Ip the usew
vag Sms, Yo
kno
infernal procetsing abeub
He, . ..
ef a class that ic dedavad with ob
is tran as abilvade class gave ak conlaint one or MOVE
alstrak methods « :
<5 an abslade clas cam have obstiout and non abstvack
melfieds.
pbstraut Mebhed :
pes nd Mave
a method that is didered af abitrad: and
| Yeplementatin is Knson as abstrad method +
@r)
fan absha method i
No body oF implementation «
enample abstr void sunt;
, abswad- void displayor;
Cee te j
a wielfod tat dedavad ith
eau etal
itl” abetead class Bike
if,
absivaut void Yunly,
I
a] ai
abshrouk class Anionsl .
t
abskauk void Seubade, me
pabshed | void eokor; ., dad
oe
Scanned by CamScannerA bstrack class ie
Import java. Lang *:
clay
abstcaue dass Robo a
Void nmalkad CD Pe Sov on C Shing arr
4 " -
£o pin c Normal mated D> Sana ob} = smeacs|
abstract Vord abmetude > Ob). Hmethed CD)
bj. .
class Sana xtenta Robo Ob): abratied cs -
{ 5
Void abmutted¢) (3
S opln¢" abmetied” >, |
jObject Class:Object Class
There is one special class, Object, defined by Java.
‘The Object class is the parent class of all the classes in java by default.
Object is a superclass of all other classes. This means that a reference variable of type Object can refer to
an object of any other class.
‘The parent class reference variable can refer the child class object, know as upcasting.Forms of Inheritance-Specialization :Forms of Inheritance-Specialization
Forms of Inheritance :
Alll objects eventually inherit from Object, which provides useful methods such as equals and toString.
In general we want to satisfy substitutability: if B is a subclass of A, anywhere we expect an instance
of A we can use an instance of B.
Inheritance gets used for a number of purposes in typical object-oriented programming:
Specification inheritance:
If the parent class it is providing a specification for the child class,
and therefore it is specification inheritance (a variety of specialization inheritance).
abstract, we often say that
Specialization inheritance:
‘The superclass just specifies which methods should be available but doesn't give code,
‘This is supported in java by interfaces and abstract methods
Construction inheritance
‘The superclass just specifies which methods should be available but doesnt give code.
This is supported in java by interfaces and abstract methods
Extension inheritance
‘The superclass is just used to provide behavior, but instances of the subclass dont really act like the
superclass. Violates substitutability, Exmample: defining Stack as a subclass of Vector. This is not clean
+ better to define Stack as having a field that holds a vector
Ifa child class generalizes or extends the parent class by providing more functionality, but does not
override any method, we call it imheritance for generalization,
175Java Programming | 176
The child class doesn't change anything inherited from the parent, it simply adds new features.
‘An example is Java Properties inheriting form Hashtable. subclass adds new methods, and perhaps
redefines inherited ones as well
Inheritance for Limitation
* Ifa child class overrides a method inherited from the parent in a way that makes it unusable (for
example, issues an error message), then we call it inheritance for limitation.
+ Forexample, you have an existing List data type that allows items to be inserted at either end, and
you override methods allowing insertion at one end in order to create a Stack.
+ Generally not a good idea, since it breaks the idea of substitution. But again, it is sometimes found
in practice. the subclass restricts the inherited behavior. Violates substitutability. Example: defining
Queue as a subclass of Dequeue.
Combination
The child class inherits features from more than one parent class. This is multiple inheritance .
Summary of Forms of Inheritance
Specialization. The child class is a special case of the parent class; in other words, the child class is al
subtype of the parent class.
Specification, The parent cliss defines behavior that is implemented in the child class but not in the
parent class.
Construction. The child class makes use of the behavior provided by the parent class, but is not a
subtype of the parent class.
Generalization. The child class modifies or overrides some of the methods of the parent class.
Extension. The child class adds new functionality to the parent class, but does not change any inherited’
behavior.
Limitation. The child class restricts the use of some of the behavior inherited from the parent class.
Variance. The child class and parent class are variants of each other, and the class-subclass relationship
is arbitrary.Benefits of Inheritance :
kkkBenefits of Inheritance
Benefit of using inheritance:
>
v
v
Acode can be used again and again
Inberitance in Java enhances the properties of the class, which means that property of the
parent class will automatically be inherited by the base class
It can define more specialized classes by adding new details.
In addition we have benefits such as
Software Reuse
* Code Sharing
‘© Improved Reliability
* Consistency of Interface
+ Rapid Prototyping
* Polymorphism
‘© Information HidingCost of Inheritance :Cost of Inheritance
> Execution speed
& Program si
> Message Passing Overhead
> Program Complexity
This does not mean you should not use inheritance, but rather than you must understand the benefits, and
weigh the benefits against the costs.
17