Total Pageviews

Thursday, February 17, 2011

Inheritance Continued....

Lets look deeply into inheritance.
Consider the following example :
public class SuperClass{
public String name = "SuperClass Name";
public static String staticName = " SuperClass Static Name";
public static String staticString = "SuperClass Staic String";

public static void printVal(){
.............
}
public void checkVal(){
........
}
}

public class SubClass extends SuperClass{
public String name = "SubClass name";
public static String staticName = "SubClass static name";
protected int staticString = 1;


public static void printVal(){
.............
}
public void checkVal(){
........
}
}

public static void main(....){
SuperClass superWithSuperCon = new SuperClass();
SuperClass superWithSubCon= new SubClass();
SubClass subWithSubCon = new SubClass();

sout(superWithSuperCon.name);
sout(superWithSuperCon.staticName); /*Though being static should have been accessed by using Class name,but java converts the same automatically at compile time(Not recommended)*/
sout(superWithSuperCon..staticString);

sout(superWithSubCon.name);
sout(superWithSubCon.staticName);
sout(superWithSubCon.staticString);

sout(subWithSubCon.name);
sout(subWithSubCon.staticName);
sout(subWithSubCon.staticString);

superWithSuperCon.printVal(); /*SuperClass methods called - Compile time binding*/
superWithSuperCon.checkVal(); /*SuperClass methods called - Run time binding*/

superWithSubCon.printVal(); /*SuperClass methods called - Compile time binding*/
superWithSubCon.checkVal(); /*SubClass methods called - Run time binding*/

subWithSubCon.printVal(); /*SubClass methods called - Run time binding*/
subWithSubCon.checkVal(); /*SubClass methods called - Run time binding*/
}
The output obtained is :
SuperClass Name
SuperClass Static Name
SuperClass Staic String
SuperClass Name
SuperClass Static Name
SuperClass Staic String
SubClass name
SubClass static name
1
The strange behaviour of variable in case 4 is because java does not supports instance variable overriding.Since static variables are class variables they are resolved during compile time only.
Note : Methods of type private/final/static or constructors are resolved at compile time only ie static binding.

No comments:

Post a Comment