Friday, August 19, 2011

Polymorphic References

class Animal{
void eat() {  System.out.print("animal");      }


class cow extends Animal
{
 void eat() {  System.out.print("cow");      }
void bulb() {    System.out.print("c");      }
}

class myMain()
{
public static void main(String[] args)
{
Animal h = new cow();
h.eat(); //Legal class animal has eat method
h.bulb();  //Illegal. Compile time error.
}

output: cow

Reason.
Animal h = new cow();

Here we created a Object of type animal and it is holding a instance of cow.
In this case the object reference h can only get the methods what are being implemented by Animal. It cannot get methods implemented by cow. So h.bulb() will throw a compile time error.

Coming to h.eat() now the method is in Animal. But as the instance is cow instance it will check if the eat method is overridden or not. If it is over ridden then it will always get the cow implementation of eat.
So the output is cow but not animal.

Happy Coding :)


No comments:

Post a Comment