Assume your instructor has chosen you for questioning, and he demands: "Explain Inheritance?". You somehow manage to utter some words "reuse", "code", "hierarchical relationship" and get the clean cheat. You get seated and wipe-off the perspiration.
If this scenario is common then you are a victim. You merely know the definition or have faint idea but do you know at what stage is inheritance comes in to the picture? Apart from by-hearting the definition, it is equally important to know how a concept is implemented. Lets have a look @ how Inheritance is implemented in Java. Beginning with process of compilation,
Assume class "Child" is child of class "Parent". We define both classes as follows:
class Parent class Child extends Parent
{ {
int a; int b;
} }
Now going by definition, we know that sub class inherits all the members of parent class, hence "Child" class should have two members conceptually:
int a;
int b;
And to verify it we create an object and try to access member a, and it works.
child ob = new Child();
ob.a = 10;
Weighing both sides,
- At code level there is no member 'int b' in child class
- At execution level Child class has the member 'int b'.
This gap is filled at compilation level and Java handles Inheritance at compile time. Thus,
Compilation includes defining structure of each class. The moment javac senses one class to be child of another, it adds all members of super class to structure of child. Thus the class layout after compilation would be...
class Parent class Child
{ {
int a; int a;
} int b;
}
Getting This? YES or NO??? Ok, Repeating once more,
Inheritance (sub-class has all the members of super-class) is detected at compile time. If any class is found to be "child" of super-class, all members of super-class is added to structure of child-class. Finally all layouts is written to .class file and thus saved.
Now that's called Understanding Inheritance. I know you will let me know what have you inherited from this post via comments.
Clean & Clear!
ReplyDeleteDear Sagar and student friends,
ReplyDeleteI think 'a'is a member of parent and 'b' is a member of child at code level. So, correct example to illustrate the concept
it should be
--------------
child ob = new Child();
ob.a = 10;
---------------
Instead of
-------------
child ob = new Child();
ob.b = 10;
----------------
Reason is 'b' is member of child itselsf at code level and 'a' becomes member of child at compile time.
Dear Sagar, I'm right or its wrong...?
-- Ramji Makwana
Thank you Sir. the mistake has been ironed out.
ReplyDelete