Thursday, January 12, 2017

Inheritance - Indepth- Important Topic of Interview of Java

Hi Guys, Yesterday I posted about Inheritance , what how and type of inheritance . today i am going to post articles about the Indepth knowledge of inheritance, So lets starts

HOW TO PREVENT THE CLASS FROM INHERITANCE
to prevent the class from inherit , we should use final modifier
Ex-
Class A{
}
Class B extends A{
}
OUTPUT - inheritance possible
final Class A{
}
Class B extends A
{
}
Output -inheritnace not possible as class is final (cannot inherit from final )

this keyword - to indicate the current object
super keyword is used to indicate the parent object of the current Object

USE OF SUPER KEYWORD IN INHERITANCE

Class Parent{

Parent()
{
syso("this is parent 0-arg constrctr");
}
}
Class Child extends Parent
{
Child()
{
this(10)    // to call child 1 args constructor
syso("child 0-arg constructor")
}
Child(int agr)
{
super()  // to call parent 0 args constructor
syso ("child 1-arg constructor");
}

psvm(string[] args)
{
new Child();
}
}
NOTE - SUPER & THIS CALL MUST BE FIRST STATEMENT IN CONSTRUCTOR
NOTE 2 - SUPER & THIS BOTH CANT BE POSSIBLE TO CALL IN SAME CONSTRUCTOR
NOTE 3- CHILD CLASS CONSTRUCTOR WILL ALWAYS CALL ANOTHER CONSTRUCTOR EITHER EXPLICIT OR IMPLICIT IF WE DON'T SPECIFY THE CONSTRUCTOR THEN SUPER() WILL BE CALLED

* compiler generated code always called zero argument constructor
* if we created one arg constructor then we will have to create zero arg constructor else it will generate compiler error

Instance block execute first then constructor execute (in inheritance case - parent class instance block then child class instance block)

Hope you guys understand the points i am trying to make, Let me know if you have any problem , Will be happy to help

-Thanks for Reading
-Noeik

0 comments:

Post a Comment