Dear Ganesh Kumar,
Let's say you created an abstract class called Shape.
AND, among many other methods that you have in this Shape class is a method called
intersects() which returns a boolean.
This method checks whether a Shape object touches another Shape object.
Now, you
could do it this way:
Basically, you would be overloading the intersects method to perform operations for different shapes.
You create subclasses such as Rectangle, Circle, etc.
You now publish your very own Shape API into this world.
Now, a person from Brazil wants to extend your Shape class and create HIS own arbitrary shape. He also wants to use your intersects() method to check whether HIS shape object touches a Rectangle, Circle, etc.
But, unfortunately,
he can't! Because you haven't specified any overloaded method in the abstract class to support HIS shape. And that person is obviously NOT allowed to change your Shape class.
So, how do you work around this?
Simple, by generalizing the parameter accepted by intersects() method to Shape type.
So, now any person from anywhere in this world could use HIS own shape and use your intersects() method simply by extending your Shape class.
So, that's the power you get by doing Shape rect = new Rectangle();
Or, as in your case, ganesh gan = new shyam();
By Ganesh Kumar,
If ganesh is super class and shyam is sub class.Can it access methods of shyam?
In the above case, ganesh gan = new shyam(), you CAN access methods of shyam only if you
explicitly downcast "gan" variable.
So, in case of
ganesh gan = new shyam()
and
ganesh gan = new ganesh(),
the difference lies in how you use those variables.
Upcasting (ganesh gan = new shyam()) can provide you a lot of power as shown above.
Regarding your last doubt, tell me, what do you mean by int i?
The same meaning holds true for ganesh gan!
It means "i" is of type int and "gan" is of type ganesh.