I have these three class
public class Abc
{
public methAbc()
{
System.out.println("parent class method");
}
}
public class Xyz extends Abc
{
public methAbc()
{
System.out.println("overriden parent class method");
}
public methXyz()
{
System.out.println("child class method");
}
}
class Pqr
{
Xyz childObjChildRef = new Xyz();
Abc childObjParentdRef = new Xyz();
}
in class Pqr what are is the main difference in creating objects in different references
1 : when hold the object in the same class reference ==> then we can call all the methods from the class
2 : when hold the object in the parent class reference ==> then we can call only the overridden methods from the class
In java you are encouraged to use, if possible, the super-type or interface that your concrete type is implementing. This decouples your code from the actual implementation of the class.
For example: imagine you are writing the main loop of a video-game. There you write your code using an Enemy interface, which has some methods (collide(), shoot(), decideNextMovement(), etc.). Once you have written your main loop in terms of this interface, it remains as is forever; however, you can always extend your videogame by adding new implementations of the Enemy interface (EnemyShip, EnemyMonster, EnemyParachuter, etc.), but you will never need to modify your main loop because of that.
This is a design principle in object oriented programming:
http://en.wikipedia.org/wiki/Open/closed_principle
Variable "childObjParentdRef" is just holding a reference to the instance of Xyz, thus, if you happen to invoke its method "methAbc", you are invoking the overridden method in Xyz although your variable is of type Abc.
So it is important to know that the "methods/behaviors" of the "super type/class" you've instantiated will 'always' be the ones invoked by the compiler even you "box" your object into its "base type/class."
Same works in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With