Monday, August 5, 2013

[PART-5] JAVA : Inheritance explained with programs

Read my previous tutorial if you have not read yet.

In my previous tutorial you learned about types of inheritance.
In this tutorial we will develop programs of :
1.) Single inheritance
2.)Multilevel inheritance
3.)Hierarchical inheritance
4.)Multiple inheritance

Let's Start:
 Below are the programs of inheritance. You have to compile and run each program.

1.)Single inheritance :

  • In this program i have declared a class a. In class a, i have declared a int type variable "p" and two functions aget() to get the value of "p" from the user and ashow() to print the value of "p" given by the user. Similarly we have declared another class "b" which contains variable "q" and functions bget() and bshow(). I have use extends keyword to inherit the features of "class a "into "class b". Then i declared the main() method and created object of "class b" as "obj", With the help of this object i can access the data members and member functions of "class a".  as well as "class b". I can access the data members and member functions of "class a" because i have inherited the features of "class a" into "class b".


2.)Multilevel inheritance

  • In this program i have declared three classes "a", "b", and "c". I have declared the data members and member functions same as above in these three classes. But here i have used extends keyword in classes "b" and "c "respectively. Now if i create a object in class 'c" then with the help of this object i can access the data members and member functions of classes a and b respectively.

3.)Hierarchical inheritance

  • In this program i have declared three classes "a", "b" and "c". I have declared data members and member functions of classes "a", "b" and "c" same as i have done above. Now if i create an object of class "b" and class "c" then with that object i can access data members and member functions class "a". I don't need to create object of class "a" to access data members and member functions of class "a".

4.)Multilevel Inheritance
This type of inheritance is not supported in Java to avoid complexity.



0 comments:

Post a Comment