Friday, March 11, 2011

Inheritance

Different kind of objects often have a certain amount in common with each other. That means some objects have same features.
As an example just think about animals. Every animal can eat and run.
Now think about a dog. Dog also an animal. It can eat and run. Other than that a dog can bark. It is a special feature of a dog.
Now think ANIMAL and DOG are two separate classes. Some features in ANIMAL class has DOG class such as eating and running.


   
 class Animal{
       eat
       run
}


class Dog{
     eat
     run
     bark
}


Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.


So the class which has only the common features becomes super class. According to this example Animal class is the super class.
Other classes are sub classes. Dog is sub class.


Java syntax for creating a sub class is very simple.




eat , run, bark are not actual coding.


According to this example ,
Dog IS A Animal. This IS A words replaced by extends key word in JAVA coding.
That means every sub class has a IS A relationship with super(parent) class.


Advantages of INHERITANCE



  • No of lines in a coding get reduced.
  • Efficient memory allocation.
  • Easy to add new features to sub classes without been removing old features.
  • Re usability  - facility to use properties of super class without rewriting. 
  • extendability - we can extend the already made classes by adding some new 
    features.


ex-




Without repeating we can use super class features.
Like this you can create any no of sub classes. But remember sub class can has only a one super class.  But super class can has any number of sub classes.

If we create an Animal object in class Dog we can only get super class features. We cannot print barking. Because Animal is the super class.

That means by creating subclasses objects we can access super class features without repeating codes. Simply that is INHERITANCE.




According to given details try to make your own java coding with using INHERITANCE concept.

IMPORTANT

class A{}
class B{}
class X extends A , B{}                             (WRONG)

one sub class can not has two or more parent. Only can has one.



-Thank you-

No comments:

Post a Comment