Inheritance is the process by which objects of one class can acquire the properties of objects of another class.In java one class implements the properties(not private) of another class by using the keyword "extends".
Types of inheritance possible :
Types of inheritance possible :
- Single / simple inhertance
- Multiple inheritance
- Hierarchical inheritance
- Multi-level inheritance
What is a constructor ?
A constructor is a special type of a function which is used to initialize the instance variables .
A constructor has the following properties
1> it has to have the same name as that of the class
2.>it does not have a return type , not even void
3.>A constructor can only be called when an object is created .It cannot be called separately unlike functions.
** The first line in the calling of a constructor is a call to its super class constructor .
Constructors can be of two types:
- Default constructor
- User-defined constructor
In case we forget to write any constructor for a class , the compiler during compilation adds a default constructor to the program automatically.
But if we have written a constructor explicitly then the compiler does not add the default constructor .
Constructor Chaining :
Calling one constructor from another constructor is called constructor chaining .
Constructor chaining only works if the classes of which the constructors are being called are the super class i.e the classes involved (Inheritance structure should be present ).
See the following example to understand more clearly
Try to understand the flow of the program .
But if we have written a constructor explicitly then the compiler does not add the default constructor .
Constructor Chaining :
Calling one constructor from another constructor is called constructor chaining .
Constructor chaining only works if the classes of which the constructors are being called are the super class i.e the classes involved (Inheritance structure should be present ).
See the following example to understand more clearly
Try to understand the flow of the program .
- in line 44 the object is created and the parameterised constructor sub2 is called .
- in line 30, the arguments sent from line 15 are received and the call on line 32 sends the control to line 20.
- in line 20, the arguments sent from line 32 are received and the call on line 22 sends the control to line5.
- here x,y get initialized with the values 10 and 20 that were sent in line 44.
- next the control passes to line 23 . Here z gets initialized with 30 (because 'w' received 30 from the caller)
- next the control passes to line 33 . Here a,b,c, gets initialized with 40,50,60 .
- now the control returns to line 45. where the value stored in x declared in class Inheritance is stored in x of class test.
- since data of another class cannot be accessed directly (security feature of java) . An object of that class was created and was used to access Inheritance class's data x through it.
No comments:
Post a Comment