Saturday, April 19, 2014

BaseClass-ChildClass Reference-Object Cases

1. BaseClass reference with BaseClass object

BaseClass bc1 = new BaseClass();
bc1.commonMethod();
BaseClass reference here has access to all the public methods and instance variables of BaseClass. So calling commonMethod will in return result in calling commonMethod of BaseClass.
Output:
Executing method of Base class

2. ChildClass reference with ChildClass object

ChildClass cc1 = new ChildClass();
cc1.commonMethod();
ChildClass reference here has access to all the public methods and instance variables of BaseClass as well as ChildClass due to concept of inheritance. So calling commonMethod will in return result in calling commonMethod of ChildClass.
Output:
Executing method of Child class

3. BaseClass reference with ChildClass object (Overriding)

BaseClass bc2 = new ChildClass();
bc2.commonMethod();
BaseClass reference here has access to all the public methods and instance variables of BaseClass as well as overridden methods of ChildClass due to concept of dynamic polymorphism. So calling commonMethod will in return result in calling commonMethod of ChildClass.
Output:
Executing method of Child class

4. ChildClass reference with BaseClass object (not possible)

ChildClass cc2 = new BaseClass();
Above statement will result in a compile time error.
Compile-time error:
Type mismatch: cannot convert from BaseClass to ChildClass
CommonMethod of that class will be called whose object is created.

0 comments:

Post a Comment