Saturday, February 8, 2014

JOlympics ( Parent Child running race to explain typecasting concept inheritance in Java)


-- Inheritance explained with an example --

Rules:

1.       All 2 competitions are for Parents AND/OR Childs
            2.       You are allowed to run in the tunnel race only of the Gate Keeper (Compiler) allows you to run;
            3.       Gate Keeper (Compiler) is a smart living Guy – as it has brain
             4.       Tunnel (JVM) is a physical concrete structure with no brain – allows anyone to run if he   manages to enter the Tunnel.
            5.       Gate Keeper allows/dis allows based on People appearance not based on People height   as he is already aware that tall people will not be able to enter the small tunnels (JVM)
            6.       Gate Keeper allows Children in Parent race as he is aware about Children efficiency and will not able to win any parent race
            7.       Only way to cheat Gate Keeper is dress yourself as parent or child (typecast)
            8.       You will be able to run only of Your height fits within the tunnel height (JVM)
            9.       Basic assumption is Parent is twice taller than Child and double fast than the Children

Parent Race:
a.       Any parent is allowed to run; Tunnel height is equal to Tallest parent height
b.      Children dressed up (typecast) as parents will also be allowed to Run as the GateKeeper (compiler) will be fooled to seeing the attire

L1: Parent p1 = new Parent();
L2: Child c1 = new Child();
L3: Parent p2 = (Parent) new Child();




L4: p1.run(); // works as it is parent race – and parent runs with his efficiency.

L5: c1.run(); // works as gate keeper allows – and child run with his own efficiency.

L6: p2.run(); // works as gate keeper is fooled – and will run with child efficiency – as it is a child dressed up (typecast) like parent.


 
Child Race:
a.       Any Childs is allowed to run; Tunnel height is equal to tallest Child height – means no parent will be able to run
b.      Parents dressed up (typecast) as Child will also be allowed to Run as the GateKeeper (compiler) will be fooled  seeing the attire

L1: Child c1 = new Child();
L2: Child c2 = new Parent(); // gate keeper (compiler) stops it – compile time error
L3: Child c3 = (Child) new Parent(); // gate keeper (compiler)  allows due to dress up (type cast)

L4: c1.run(); // works as it is nothing special – runs with child efficiency
L5: c3.run(); // run time error – as C3 is parent dressed up(type cast) as child and since parent is taller than the tunnel height will not be able to run;

 
Best Regards
Anu