April 04, 2012

Real world example for Abstract Class in java


Real world example for Abstract Class in java


Abstract class is a class that contains abstract method and non abstract methods. Sub class which extends the abstract class "must" implements the abstract methods in the abstract class.
For examples.
Let us consider animal as our abstract class. I wrote 2 function in it. One breath() , breath is a non abtract method.
please consider every animal breath in a common way. so i write some code inside the function breath(). let it be a "Through respiratory system"

second function is a abstract method lifespan(), lifespan is different for each types of animals.

now consider sub class as dog , cat and ant

these class extends that abstract class. The relation ship will come in this way like dog is an animal, cat is a animal ..."is - a" relation ship
since the sub class extends the base class animal.. we need to define lifespan() function in each subclass.

lifespan() is different for each animal

for cat its 25, dog 22 and ant 3.

while i create an object Animal a = new cat();
a.breath()  will return me   "Through respiratory system" and
a.lifespan() will return me  25

if i create an object Animal a = new dog();
a.breath() ---->  "Through respiratory system"
a.lifespan() -----> 22

got it !!!!


Author +belazy 


Thanking you...................

Facebook comments