Sie sind auf Seite 1von 26

UNIT III Inheritance

Inheritance
Inheritance: Inheritance is the process by which objects of one class acquire the
properties of objects of another class. Inheritance supports the concept of hierarchical
classification. A deeply inherited subclass inherits all of the attributes from each of its
ancestors in the class hierarchy.
Most people naturally view the world as made up of objects that are related to each other in
a hierarchical way.
Inheritance: A new class (subclass, child class) is derived from the existin class (base
class, parent class).
Main uses of Inheritance: !. "eusability #. Abstraction
Syntax:
class $ub%classname extends $uper%classname
& 'eclaration of variables(
'eclaration of methods(
)
Super class: In *ava a class that is inherited from is called a super class.
Sub class: +he class that does the inheritin is called as subclass. It inherits all of the
instance variables and methods defined by the superclass and add its own, unique
elements.
OOP Through JAA N!"# "S! $ept% Page &
UNIT III Inheritance
+he ,extends- .eyword indicates that the properties of the super class name are
extended to the subclass name. +he sub class now contains its own variables and
methods.
'' A si(ple exa(ple of
inheritance%
// create a superclass.
class A
&
int i, j(
void showij()
&
$ystem.out.println(0i and j1 0 2 i 2 0
0 2 j)(
)
)
// create a subclass by extendin
class A.
class 3 extends A
&
int .(
void show.()
&
$ystem.out.println(0.1 0 2 .)(
)
void sum() &
$ystem.out.println(0i2j2.1 0 2
(i2j2.))(
)
)
class $impleInheritance
&
public static void main($trin
ars45)
&
A super6b 7 new A()(
3 sub6b 7 new 3()(
// +he superclass may be used by
itself.
super6b.i 7 !8(
super6b.j 7 #8(
$ystem.out.println(09ontents of
super6b1 0)(
super6b.showij()(
$ystem.out.println()(
/: +he subclass has access to all
public members of
its superclass. :/
sub6b.i 7 ;(
sub6b.j 7 <(
sub6b.. 7 =(
$ystem.out.println(09ontents of
sub6b1 0)(
sub6b.showij()(
sub6b.show.()(
$ystem.out.println()(
$ystem.out.println(0$um of i, j and
. in sub6b10)(
sub6b.sum()(
)
)
Output:
'1>?javac $impleInheritance.java
'1>?java $impleInheritance
9ontents of super6b1
i and j1 !8 #8
9ontents of sub6b1
i and j1 ; <
.1 =
$um of i, j and . in sub6b1
i2j2.1 #@
)ierarchical abstractions:
OOP Through JAA N!"# "S! $ept% Page *
UNIT III Inheritance
Aierarchical abstractions of complex systems can also be applied to
computer prorams. +he data from a traditional process%oriented proram
can be transformed by abstraction into its component objects.
A sequence of process steps can become a collection of messaes between
these objects. +hus, each of these objects describes its own unique
behavior.
Bou can treat these objects as concrete entities that respond to messaes
tellin them to do somethin. +his is the essence of object%oriented
prorammin.
+ypes of Inheritance are used to show the Aierarchical abstractions. +hey
are1
$inle Inheritance, Multiple Inheritance, Aierarchical Inheritance,
Multilevel Inheritance, and Aybrid Inheritance.
Single Inheritance: $imple Inheritance is also called as sinle Inheritance.
Aere one subclass is derivin from one super class.
$uper 9lass $ub 9lass
!xa(ple:
import java.io.:(
class A
&
void display()
&
$ystem.out.println(0hi-)(
)
)
class 3 extends A
&
void display()
&
$ystem.out.println(0hello0)(
)
)
class Inh
&
public static void
main($trin ars45)
&
3 b7new 3()(
b.display()(
)
)
Output:
'1>?javac Inh.java
OOP Through JAA N!"# "S! $ept% Page +
A 3
UNIT III Inheritance
'1>?java Inh
hello
Multiple Inheritance: 'erivin one subclass from more than one super
classes is called multiple inheritance.
IC+D"EA9D! IC+D"EA9D#

(Animal) (3ird)
IMFGDMDC+$
$H39GA$$ (Interface'emo#)
In multiple inheritance, sub class is derived from multiple super classes. If
two super classes have same names for their members then which member is
inherited into the sub class is the main confusion in multiple inheritance. +his
is the reason( Java does not support the concept of multiple inheritance. +his
confusion is reduced by usin multiple interfaces to achieve the concept of
multiple inheritance.
Interface: An interface is a class containin a roup of constants and method
declarations that does not provide implementation. In essence, an interface
allows you to specify what a class must do, but not how to do.
Interface syntax:
access interface name
&
return%type method%name!(parameter%list)(
return%type method%name#(parameter%list)(
type varname! 7 value(
type varname# 7 value(
// ...
return%type method%nameC(parameter%list)(
type varnameC 7 value(
)
OOP Through JAA N!"# "S! $ept% Page ,
A B
UNIT III Inheritance
By default all the methods in an interface must be abstract and public. If
we do not mention these keywords the JVM will treat all these methods
as public and abstract implicitly.
All the constants are treated as public, final and static.
!xa(ple:
interface Animal
&
public abstract void moves()(
)
interface 3ird
&
void fly()(
)
public class Interface'emo#
implements Animal, 3ird
&
public void moves()
&
$ystem.out.println(0animal move
on land0)(
)
public void fly()
&
$ystem.out.println(0birds fly in
air0)(
)
public static void main($trin
ars45)
&
Interface'emo# id7new
Interface'emo#()(
id.moves()(
id.fly()(
)
)
Output:
'1>?javac Interface'emo#.java
'1>?java Interface'emo#
animal move on land
birds fly in air
)ierarchical Inheritance: 6nly one base class but many derived classes.

$HFD"9GA$$
DI+DC'$
$H39GA$$
!xa(ple:
abstract class Eiure
&
double dim!(
double dim#(
OOP Through JAA N!"# "S! $ept% Page -
Eiure
"ectanle +rianle
UNIT III Inheritance
Eiure(double a, double b)
&
dim! 7 a(
dim# 7 b(
)
// area is now an abstract method
abstract double area()(
)
class "ectanle extends Eiure
&
"ectanle(double a, double b)
&
super(a, b)(
)
// override area for rectanle
double area()
&
$ystem.out.println(0Inside Area for
"ectanle.0)(
return dim! : dim#(
)
)
class +rianle extends Eiure
&
+rianle(double a, double b)
&
super(a, b)(
)
// override area for riht trianle
double area()
&
$ystem.out.println(0Inside Area for
+rianle.0)(
return dim! : dim# / #(
)
)
class AbstractAreas
&
public static void main($trin
ars45)
&
// Eiure f 7 new Eiure(!8, !8)( //
illeal now
"ectanle r 7 new "ectanle(=, J)(
+rianle t 7 new +rianle(!8, <)(
Eiure firef( // this is 6K, no
object is created
firef 7 r(
$ystem.out.println(0Area is 0 2
firef.area())(
firef 7 t(
$ystem.out.println(0Area is 0 2
firef.area())(
)
)
Output:
'1>?javac AbstractAreas.java
'1>?java AbstractAreas
Inside Area for "ectanle.
Area is @J.8
Inside Area for +rianle.
Area is @8.8
Multile.el Inheritance: In multilevel inheritance the class is derived from the
derived class.
OOP Through JAA N!"# "S! $ept% Page /
A 3 9
UNIT III Inheritance
!xa(ple:
// 9reate a super class.
class A
&
A()
&
$ystem.out.println(0Inside ALs
constructor.0)(
)
)
// 9reate a subclass by extendin
class A.
class 3 extends A
&
3()
&
$ystem.out.println(0Inside 3Ls
constructor.0)(
)
)
// 9reate another subclass by
extendin 3.
class 9 extends 3
&
9()
&
$ystem.out.println(0Inside 9Ls
constructor.0)(
)
)
class 9allin9ons
&
public static void main($trin
ars45)
&
9 c 7 new 9()(
)
)
Output :
'1>?javac 9allin9ons.java
'1>?java 9allin9ons
Inside ALs constructor.
Inside 3Ls constructor.
Inside 9Ls constructor.
)ybrid Inheritance: It is a combination of multiple and hierarchical
inheritance.
AID"A"9AI9AG
MHG+IFGD
OOP Through JAA N!"# "S! $ept% Page 0
B
A
D
C
UNIT III Inheritance
Super Uses: Mhenever a subclass needs to refer to its immediate super
class, it can do so by the use of the .eyword super.
$uper has the two eneral forms.
super (ars%list) 1 calls the $uper classNs constructor.
super%member1 +o access a member of the super class that has been hidden
by a member of a subclass. Member may be variable or method.
The 1ey2ord 3super4:
super can be used to refer super class variables as1 super%.ariable
super can be used to refer super class methods as1 super%(ethod 56
super can be used to refer super class constructor as1 super 5.alues6
&% Accessing the super class constructor: super (parameterOlist) calls the
super class constructor. +he statement callin super class constructor should be
the first one in sub class constructor.
!xa(ple progra( for super can be used to refer super class constructor
as: super 5.alues6
class Eiure
&
double dim!(
double dim#(
Eiure(double a, double b)
&
dim!7a(
dim#7b(
)
)
class "ectanle extends Eiure
&
"ectanle(double a,double b)
&
super(a,b)(//calls super class
constructor
)
double area()
&
$ystem.out.println(0Inside area for
rectanle0)(
return dim!:dim#(
)
)
class +rianle extends Eiure
&
+rianle(double a,double b)
&
super(a,b)(
)
double area()
&
$ystem.out.println(0Inside area for
trianle0)(
return dim!:dim#/#(
)
)
class EindAreas
&
OOP Through JAA N!"# "S! $ept% Page 7
UNIT III Inheritance
public static void main($trin
ars45)
&
"ectanle r7new "ectanle(=,J)(
+rianle t7new +rianle(!8,<)(
$ystem.out.println(0area
is02r.area())(
$ystem.out.println(0area
is02t.area())(
)
)
Output:
'1>?javac EindAreas.java
'1>?java EindAreas
Inside area for rectanle
area is@J.8
Inside area for trianle
area is@8.8
*% Accessing the (e(ber of a super class: +he second form of super acts
somewhat li.e this, except that it always refers to the superclass of the
subclass in which it is used.
Syntax: super% member(
Aere, member can be either a method or an instance variable. +his second form
of super is most applicable to situations in which member names of a subclass
hide members by the same name in the superclass. 9onsider this simple class
hierarchy1
// Hsin super to overcome name
hidin.
class A
&
int i(
)
// 9reate a subclass by extendin
class A.
class 3 extends A
&
int i( // this i hides the i in A
3(int a, int b)
&
super.i 7 a( // i in A
i 7 b( // i in 3
)
void show()
&
$ystem.out.println(0i in superclass1
0 2 super.i)(
$ystem.out.println(0i in subclass1 0
2 i)(
)
)
class Hse$uper
&
public static void main($trin
ars45)
&
3 sub6b 7 new 3(!, #)(
sub6b.show()(
)
)
Output:
'1>?javac Hse$uper.java
'1>?java Hse$uper
i in superclass1 !
i in subclass1 #
OOP Through JAA N!"# "S! $ept% Page 8
UNIT III Inheritance
Super uses: super class4s (ethod access
import java.io.:(
class A
&
void display()
&
$ystem.out.println(0hi0)(
)
)
class 3 extends A
&
void display()
&
super.display()(// calls super class
display()
$ystem.out.println(0hello0)(
)
static public void main($trin
ars45)
&
3 b7new 3()(
b.display()(
)
)
Output:
'1>?javac 3.java
'1> ?java 3
hi
hello
Note: Super 1ey 2ord is used in sub class only%
Abstract classes:
A method with method body is called concrete method. In eneral any
class will have all concrete methods.
A method without body is called abstract method.
Syntax: abstract datatype methodname(parameter%list)(
A class that contains abstract method is called abstract class.
It is possible to implement the abstract methods differently in the
subclasses of an abstract class.
+hese different implementations will help the prorammer to perform
different tas.s dependin on the need of the sub classes. Moreover, the
common members of the abstract class are also shared by the sub classes.
+he abstract methods and abstract class should be declared usin the
.eyword abstract.
Me cannot create objects to abstract class because it is havin incomplete
code. Mhenever an abstract class is created, subclass should be
created to it and the abstract methods should be implemented in the
subclasses, then we can create objects to the subclasses.
OOP Through JAA N!"# "S! $ept% Page &9
UNIT III Inheritance
An abstract class is a class with Pero or more abstract methods
An abstract class contains instance variables Q concrete methods in
addition to abstract methods.
It is not possible to create objects to abstract class.
3ut we can create a reference of abstract class type.
All the abstract methods of the abstract class should be implemented in its
sub classes.
If any method is not implemented, then that sub class should be declared as
abstract.
Abstract class reference can be used to refer to the objects of its sub
classes.
Abstract class references cannot refer to the individual methods of sub
classes.
A class cannot be both RabstractN Q RfinalN.
e%g%: final abstract class A // invalid
Abstraction refers to the act of representin essential features without
includin the bac.round details or explanations. 9lasses use the concept of
abstraction and are defined as a list of attributes and methods to operate on
these attributes. +hey encapsulate all the essential features of the objects that
are to be created since the classes use the concept of data abstraction they are
.nown as Abstract 'ata +ypes.
An abstract class can be sub classed and canNt be instantiated.
!xa(ple: // Hsin abstract
methods and classes.
abstract class Eiure
&
double dim!,dim#(
Eiure (double a, double b)
&
dim! 7 a(
dim# 7 b(
)
abstract double area()(//an abstract
method
)
class "ectanle extends Eiure
&
"ectanle (double a, double b)
&
super (a, b)(
)
double area () // override area for
rectanle
OOP Through JAA N!"# "S! $ept% Page &&
UNIT III Inheritance
&
$ystem.out.println (0Inside Area of
"ectanle.0)(
return dim! : dim#(
)
)
class +rianle extends Eiure
&
+rianle (double a, double b)
&
super (a, b)(
)
double area() // override area for
trianle
&
$ystem.out.println (0Inside Area of
+rianle.0)(
return dim! : dim# / #(
)
)
class AbstractAreas
&
public static void main($trin
ars45)
&
// Eiure f 7 new Eiure(!8, !8)( ''
illegal no2
"ectanle r 7 new "ectanle(=, J)(
+rianle t 7 new +rianle(!8, <)(
$ystem.out.println(0Area is 0 2
r.area())(
$ystem.out.println(0Area is 0 2
t.area())(
)
)
Output:
'1>?javac AbstractAreas.java
'1>?java AbstractAreas
Inside area for "ectanle.
Area is @J.8
Inside are for +rianle.
Area is @8.8
:ase class Ob;ect or The Ob;ect class:
Ob;ect class: Super class for all the classes in java includin user defined
classes directly or indirectly.
I(porting Ob;ect class: *ava Gibrary
Gan pac.ae
6bject class
6bject class is implicitly (automatically) imported into our source code,
because it is in !lan"# pac.ae. Gan pac.ae is also implicitly imported into
every java proram.
6bject class reference can store any reference of any object. +his means that a
reference variable of type 6bject can refer to an object of any other class.
Ad.antage: Mhen we want to write a method that needs to handle objects if
un.nown type. If we define a parameter of object type, any class object can be
OOP Through JAA N!"# "S! $ept% Page &*
UNIT III Inheritance
passed to the method. +hus the method can receive any type of object and
handle it.
Method $escription
boolean equals(6bject obj) +his method compares the references of
two objects and if they are equal, it returns
true, otherwise false.
$trin to$trin() +his method returns a strin representation
of an object.
9lass et9lass() +his method ives an object that contains
the name of a class to which an object
belons. 6btains the class of an object at
run time.
int hash9ode( ) "eturns the hash code associated with the
invo.in object. +his method returns hash
code number of an object.
void notify( ) +his method sends a notification to a thread
which is waitin for an object.
void notifyAll( ) +his method sends a notification for all
waitin threads for the object.
void wait( ) +his method causes a thread to wait till a
notification is received from a notify() or
notifyAll() methods.
6bject clone( ) +his method creates a bitwise exact copy of
an existin object. 9reates a new object
that is the same as the object bein cloned.
void finaliPe( ) 9alled before an unused object is recycled.
+his method is called by the arbae
collector when an object is removed from
memory.
OOP Through JAA N!"# "S! $ept% Page &+
UNIT III Inheritance
Subclass: when a new class is constructed usin inheritance and contains
an RextendsN .eyword in the proramNs source description then that class is
said to be subclass. Senerally, a subclass is similar to a subtype.
Inheritance is a concept where subclass (new classes) can be produced from
existin classes (super class).+he newly created subclass acquires all the
features of existin classes from where it is derived.
class subclassname extends superclassname
&
)
Subtype: A subtype is a class that satisfies the principle of
substitutability. +he term subtype is used to describe the relationship between
types that explicitly reconiPes the principle of substitution. A type 3 is
considered to be a subtype of A, if instances of 3 can leally be assined to a
variable declared as of type A.
Cote1 Cot all subclasses are subtypes, and (at least in some lanuaes) you can
construct subtypes that are not subclasses.
Substitutability: Means the type of a variable can differ from the type of
the value stored in that variable. Mhen interfaces are used, there will be a
possibility of the occurrence of substitutability.
It is fundamental to many of the powerful software development
techniques in 66F.
+he idea is that, declared a variable in one type may hold the value of
different type.
$ubstitutability can occur throuh use of inheritance, whether usin
extends, or usin i(ple(ents .eywords.
Mhen new classes are constructed usin inheritance, the arument used to
justify the validity of substitutability is as follows(
Instances of the subclass must possess all data fields associated with its
parent class.
OOP Through JAA N!"# "S! $ept% Page &,
UNIT III Inheritance
Instances of the subclass must implement, throuh inheritance at least, all
functionality defined for parent class. ('efinin new methods is not
important for the arument.)
+hus, an instance of a child class can mimic the behavior of the parent
class and should be indistinguishable from an instance of parent class if
substituted in a similar situation
<eferenced $ata Types: class is a references data type. It is used to store the
several values. 9onvertin a class into another class type is also possible
throuh castin. 3ut the classes should have some relationship between them
by the way of inheritance.
!xa(ple: Bou cannot convert a 'o class into a Aorse class, as those classes
do not have any relationship between them. 3ut you can convert a 9ollee
class into a Hniversity class, since 9ollee is derived from Hniversity. And
you can convert a 'epartment class into a 9ollee, since 'epartment is
subclass of 9ollee class.
Hniversity $uper class
9ollee $ub class
'epartment sub%sub class
=or(s of Inheritance:
+he various forms of inheritance are,
!) $pecialiPation #) $pecification T) 9onstruction
@) Dxtension J) Gimitation U) 9ombination
Speciali>ation:
Inheritance is commonly used for specialiPation purpose. Aere, a child class or
a new class is a specialiPed form of the parent class and it conforms to all
specifications of the parent. +hus, a subtype (sub class) is created usin this
form and the substitutability is also maintained explicitly.
OOP Through JAA N!"# "S! $ept% Page &-
UNIT III Inheritance
!xa(ple progra(:
class 6ne
&
public void show!()
&
$ystem.out.println(0Aello0)(
)
)
class +wo extends 6ne
&
)
class $pecialiPation'emo
&
public static void main($trin
ars45)
&
+wo tw7 new +wo()(
6ne o7tw(
o.show!()(
o.show!()(
)
)
Output:
'1> ?javac
$pecialiPation'emo.java
'1>?java $pecialiPation'emo
Aello
Aello
Specification:
Inheritance can also be used to allow the classes to implement those methods
that have the same names. +he parent class can define operations with or
without implementations. +he operation whose implementation is not defined
in the parent class will be defined in the child class. $uch .ind of parent class
that defines abstract methods is also called as ,abstract specification class-.
+o support inheritance of specification, java lanuae provides two different
techniques. +hey are,
!. Hsin interfaces #. Hsin classes
&% Using interfaces exa(ple
progra(:
interface Animal
&
void moves()(
)
interface 3ird
&
void fly()(
)
public class Interface'emo#
implements Animal, 3ird
&
public void moves()
&
$ystem.out.println(0animals move
on land0)(
)
public void fly()
&
$ystem.out.println(0birds fly in
air0)(
)
OOP Through JAA N!"# "S! $ept% Page &/
UNIT III Inheritance
public static void main($trin
ars45)
&
Interface'emo# id7new
Interface'emo#()(
id.moves()(
id.fly()(
)
)
Output:
'1>?javac Interface'emo#.java
'1>?java Interface'emo#
animals move on land
birds fly in air
*% Using classes exa(ple
progra(:
import java.io.:(
abstract class A
&
abstract void display()(
)
class 3 extends A
&
void display()
&
$ystem.out.println(0hello0)(
)
public static void main($trin
ars45)
&
3 b7new 3()(
b.display()(
)
)
Output:
'1>?javac 3.java
'1>?java 3
hello
"onstruction: 9hild class inherits most of its functionality from parent,
but may chane the name or parameters of methods inherited from parent class
to form its interface.
+his type of inheritance is also widely used for code reuse purposes. It
simplifies the construction of newly formed abstraction but is not a form of
subtype, and often violates substitutability.
!xa(ple progra(:
import java.io.:(
class A
&
void display()
&
$ystem.out.println (0hi0)(
)
)
class 3 extends A
&
void display()
&
$ystem.out.println (0hello0)(
)
public static void main($trin
ars45)
OOP Through JAA N!"# "S! $ept% Page &0
UNIT III Inheritance
&
A a7new A()(
3 b7new 3()(
a.display()(
b.display()(
)
)
Output:
'1>?javac 3.java
'1>java 3
hi
hello
!xtension: +he sub classification for extension is achieved if a child
class adds an additional behavior to the parent class without modifyin the
attributes that are inherited from that parent class. +he parent class
functionality is made available to its child class without any modifications.
+hus, such classes are also the subtypes because the sub classification for
extension also supports the substitutability principle.
!xa(ple progra(:
class one
&
void disp()
&
$ystem.out.println(0hi0)(
)
)
class two extends one
&
void displ()
&
$ystem.out.println(0hello0)(
)
)
class exten
&
public static void main($trin
ars45)
&
one o7new one()(
two t7new two()(
t.disp()(
t.displ()(
)
)
Output:
'1>?javac exten.java
'1>?java exten
hi
hello
welcome
?i(itation: If a subclass restricts few behaviors to be used that are
inherited from the parent class, then the sub classification for limitation was
occurred. $ubclassification for limitation occurs when the behavior of the
subclass is smaller or more restrictive that the behavior of its parent class.
Gi.e subclassification for extension, this form of inheritance occurs most
frequently when a prorammer is buildin on a base of existin classes. Is not
a subtype, and substitutability is not proper.
OOP Through JAA N!"# "S! $ept% Page &7
UNIT III Inheritance
!xa(ple progra( for ?i(itation
is using final methods 2ith
inheritance:
import java.io.:(
class A
&
final void display()(
)
class 3 extends A
&
void display()
&
$ystem.out.println(0hello0)(
)
public static void main($trin
ars45)
&
3 b7new 3()(
b.display()(
)
)
Output:
'1>?javac 3.java
3.java1@1 missin method body, or
declare abstract
final void display()(
V
3.java1<1 display() in 3 cannot
override display() in A( overridden
method is final
void display()
V
# errors
"o(bination: *ava lanuae does not allow a subclass to inherit more
than one class. +hus, solution for this problem is to extend a parent class and
implement any number of interfaces.
!xa(ple progra( is (ultiple
inheritance%
interface Animal
&
public abstract void moves()(
)
interface 3ird
&
void fly()(
)
public class Interface'emo#
implements Animal,3ird
&
public void moves()
&
$ystem.out.println(0animals move
on land0)(
)
public void fly()
&
$ystem.out.println(0birds fly in
air0)(
)
public static void main($trin
ars45)
&
Interface'emo# id7new
Interface'emo#()(
id.moves()(
id.fly()(
)
)
Output:
'1>?javac Interface'emo#.java
'1>java Interface'emo#
animals move on land
birds fly in air
Su((ary of =or(s of Inheritance:
OOP Through JAA N!"# "S! $ept% Page &8
UNIT III Inheritance
Speciali>ation: +he child class is a special case of the parent class( in other
words, the child class is a subtype of the parent class.
Specification: +he parent class defines behavior that is implemented in the
child class but not in the parent class.
"onstruction: +he child class ma.es use of the behavior provided by the
parent class, but is not a subtype of the parent class.
@enerali>ation: +he child class modifies or overrides some of the methods
of the parent class.(widenin. up%castin)
!xtension: +he child class adds new functionality to the parent class, but
does not chane any inherited behavior.
?i(itation: +he child class restricts the use of some of the behavior
inherited from the parent class.
:enefits of Inheritance:
Increased <eliability: If a code is frequently executed then it will have
very less amount of bus, compared to code that is not frequently executed.
(error free code)
Soft2are reusability: properties of a parent class can be inherited by a
child class. 3ut, it does not require rewritin the code of the inherited
property in the child class. In 66Fs, methods can be written once but can
be reused.
"ode sharing: At one level of code sharin multiple projects or users can
use a sinle class.
Soft2are co(ponents: Frorammers can construct software components
that are reusable usin inheritance.
"onsistency of interfaces: when multiple classes inherit the behavior of a
sinle super class all those classes will now have the same behavior.
Poly(orphis(: 6ops follows the bottom%up approach. And abstraction is
hih at top, these are exhibit the different behaviors based on instances.
OOP Through JAA N!"# "S! $ept% Page *9
UNIT III Inheritance
Infor(ation hiding: interfaceNs or abstracts classesN methods definition is
in super class, methods implementation is in subclasses. Means we .now
what to do but not how to do.
<apid prototyping: 3y usin the same code for different purposes, we can
reduce the lenthy code of the proram.
"osts of inheritance:
Progra( si>e: If the cost of memory decreases, then the proram siPe does
not matter. Instead of limitin the proram siPes, there is a need to produce
code rapidly that has hih quality and is also error%free.
!xecution speed: +he specialiPed code is much faster than the inherited
methods that manae the random subclasses.
Progra( co(plexity: 9omplexity of a proram may be increased if
inheritance is overused.
MessageApassing: +he cost of messae passin is very less when
execution speed is considered.
Using final 2ith inheritance:
Einal is a .eyword in *ava which enerically means, cannot be chaned once
created. Einal behaves very differently for variables, methods and classes.
A final variable cannot be reassined once initialiPed.
A final method cannot be overridden.
A final class cannot be extended.
9lasses are usually declared final for either performance or security
reasons.
=inal 2ith .ariables: Einal variables wor. li.e constants of 9%lanuae that
canNt be altered in the whole proram. +hat is, final variables once created
canNt be chaned and they must be used as it is by all the proram code.
!xa(ple progra(:
import java.io.:(
class EinalWar
&
OOP Through JAA N!"# "S! $ept% Page *&
UNIT III Inheritance
int x7!8(
final int y7#8(
$ystem.out.println(0x is102x)(
$ystem.out.println(0y is102y)(
x7T8(
y7@8(
$ystem.out.println(0x is102x)(
$ystem.out.println(0y is102y)(
)
)
Output:
9annot assin a value to final
variable y
=inal 2ith (ethods: Senerally, a super class method can be overridden by the
subclass if it wants a different functionality. 6r, it can call the same method if
it wants the same functionality. If the super class desires that the subclass
should not override its method, it declares the method as final. +hat is,
methods declared final in the super class can not be overridden in the subclass
(else it is compilation error). 3ut, the subclass can access with its object as
usual.
!xa(ple progra(:
import java.io.:(
class A
&
final void display()
&
$ystem.out.println(0hi0)(
)
)
class 3 extends A
&
void display()
&
super.display()(
$ystem.out.println(0hello0)(
)
public static void main($trin
ars45)
&
3 b7new 3()(
b.display()(
)
)
Output:
'isplay() in 3 cannot override
display() in A( overridden method
is final.
=inal 2ith classes: If we want the class not be sub%classed (or extended) by
any other class, declare it final. 9lasses declared final can not be extended.
+hat is, any class can use the methods of a final class by creatin an object of
the final class and call the methods with the object (final class object).
!xa(ple progra(:
import java.io.:(
final class 'emo!
&
public void display()
&
$ystem.out.println(0hi0)(
)
OOP Through JAA N!"# "S! $ept% Page **
UNIT III Inheritance
)
public class 'emoT extends 'emo!
&
public static void main($trin
ars45)
&
'emo! d7new 'emo!()(
d.display()(
)
)
Output:
'1>?javac 'emoT.java
'emoT.java1=1 cannot inherit from
final 'emo!
public class 'emoT extends 'emo!
V
! error
Poly(orphis(:
Folymorphism came from the two Sree. words RpolyN means many and
RmorphosN means forms.
If the same method has ability to ta.e more than one form to
perform several tas.s then it is called polymorphism.
It is of two types1
'ynamic polymorphism("untime polymorphism)
$tatic polymorphism(9ompile time polymorphism)
$yna(ic Poly(orphis(: +he polymorphism exhibited at run time is called
dynamic polymorphism. In this dynamic polymorphism a method call is lin.ed
with method body at the time of execution by *WM. *ava compiler does not
.now which method is called at the time of compilation. +his is also .nown
as dynamic bindin or run time polymorphism.
Method o.erloading and (ethod o.erriding are exa(ples of $yna(ic
Poly(orphis( in Ja.a%
Method O.erloading: Mritin two or more methods with the same
name with different parameters is called method over loadin.. In method
overloadin *WM understands which method is called dependin upon the
difference in the method parameters. +he difference may be due to the
followin1
OOP Through JAA N!"# "S! $ept% Page *+
UNIT III Inheritance
X +here is a difference in the no. of parameters.
void add (int a,int b)
void add (int a,int b,int c)
X +here is a difference in the data types of parameters.
void add (int a,float b)
void add (double a,double b)
X +here is a difference in the sequence of parameters.
void swap (int a,char b)
void swap (char a,int b)
// overloadin of methods %%%%%%%%% 'ynamic polymorphism
class $ample
&
void add(int a, int b)
&
$ystem.out.println (0sum of two702 (a2b))(
)
void add(int a, int b, int c)
&
$ystem.out.println (0sum of three702 (a2b2c))(
)
)
class 6verGoad
&
public static void main($trin45 ars)
&
$ample s7new $ample ( )(
s.add (#8, #J)(
s.add (#8, #J, T8)(
)
)
Output:
'1>?javac 6verGoad.java
'1>java 6verGoad
sum of two7@J
sum of three7;J
Method O.erriding: Mritin two or more methods in super Q sub
classes with same name and same parameters is called method overridin. In
method overridin *WM executes a method dependin on the type of the
object.
//overridin of methods %%%%%%%%%%%%%%% 'ynamic polymorphism
OOP Through JAA N!"# "S! $ept% Page *,
UNIT III Inheritance
class Animal
&
void move()
&
$ystem.out.println (0Animals can move0)(
)
)
class 'o extends Animal
&
void move()
&
$ystem.out.println (0'os can wal. and run0)(
)
)
public class 6ver"ide
&
public static void main($trin ars45)
&
Animal a 7 new Animal ()( // Animal reference and object
Animal b 7 new 'o ()( // Animal reference but 'o object
a.move ()( // runs the method in Animal class
b.move ()( //"uns the method in 'o class
)
)
Output:
'1>?javac 6ver"ide.java
'1>?java 6ver"ide
Animals can move
'os can wal. and run
Achievin method overloadin Q method overridin usin instance methods is
an example of dynamic polymorphism.
Static Poly(orphis(: +he polymorphism exhibited at compile time is called
$tatic polymorphism. Aere the compiler .nows which method is called at the
compilation. +his is also called compile time polymorphism or static bindin.
Achievin method overloadin Q method overridin usin private, static
and final methods is an example of $tatic Folymorphism.
//$tatic Folymorphism
class Animal
&
OOP Through JAA N!"# "S! $ept% Page *-
UNIT III Inheritance
static void move ()
&
$ystem.out.println (0Animals can move0)(
)
)
class 'o extends Animal
&
static void move ()
&
$ystem.out.println (0'os can wal. and run0)(
)
)
public class $taticFoly
&
public static void main($trin ars45)
&
Animal.move ()(
'o.move ()(
)
)
Output:
'1>?javac $taticFoly.java
'1>?java $taticFoly
Animals can move
'os can wal. and run
OOP Through JAA N!"# "S! $ept% Page */

Das könnte Ihnen auch gefallen