Originally posted by sravanthi pulukuri:
class Bird
{
void talk() { System.out.print("chirp ");
}
}
class Parrot2 extends Bird
{
protected void talk() { System.out.print("hello ");
}
public static void main(String [] args)
{
Bird [] birds = {new Bird(), new Parrot2()
};
for( Bird b : birds)
b.talk();
}
}
Can anyone explain why teh output is getting as
Chrk,hello
Explain please
Hi,
In one
word, you see the
Polymorphism there.
Parrot has overridden the Bird method talk() with more public access that is
in the Bird class it has default access whereas in the subclass Parrot
it it protected (hence more public).
You have created a Bird array. Its elements hold reference of Bird as
well object of the Bird's subclasses object. Method selection will be done at run time on behalf of what object the ref variable is holding. First
element holds object of Bird so Bird's talk() method is selected and in the
second iteration because the object is now Parrot, talk() method of the
Parrot is selected.
Thanks,
[ May 15, 2007: Message edited by: Chandra Bhatt ]