Originally Posted by
gautammuktsar@gmail.com
By this version we get the same result but why we use 1st version means access the method by superclass reference ..Is there any rule under Polymorphism like this .. if it is then i don't know as i am new to java ..please explain me
For your simple Test class, there is no real difference between using the more generic Bank or the more specific sub types.
If you invoke getRateOfInterest on a Bank reference you do what is called a "polymorphic invocation": the version of the getRateOfInterest that is executed is choosen at
runtime, basing on the
real object that the reference points to.
So your doubt is: why use a Bank reference type? Simple: you can have a method that has a Bank parameter. Ideally it should work with any object that is a subtype of Bank. And you can have a method that has Bank as return type. It may return an object of one of the subtypes of Bank.
You can have, say, a method that selects the "best" between 2 Bank objects by its rate of interest:
public static Bank selectBestBankByRate(Bank b1, Bank b2) {
if (b1.getRateOfInterest() >= b2.getRateOfInterest()) {
return b1;
} else {
return b2;
}
}
This method doesn't know anything about any of the specific sub types of Bank. But it works with any of them. This is the real power of the polymorphism.
Final note: in theory, your Bank class can/should be "abstract", with an abstract getRateOfInterest (no body { ... }). Exactly like, other example, Animal class and Cat, Dog subclasses. It has no much sense to instantiate an Animal .... Animal what? Instead, Cat and Dog are more concrete types.