Polymorphism

A forum to discuss Java programming related issues and concerns.
no avatar
maksud89
 
Posts: 1
Joined: Sun Nov 20, 2011 10:40 am

Polymorphism

by maksud89 » Sun Nov 20, 2011 10:54 am

Hi All, I am new in this site. I would be very grateful if you could answer my follwing question. Thanx advance for ur time.



public abstract class Animal {

void getName(){

System.out.println("Base class");

}
}


class Dog extends Animal{

void getName(){

System.out.println("Its a dog");

}

}


class Cat extends Animal{

void getName(){

System.out.println("Its a cat");

}

}




class Test {
public static void main(String[] args) {

//Animal a=new Dog(); //Animal type but refer Dog......??????
//Animal b= new Cat(); //Animal Type but refer cat.......??????

Dog a=new Dog();
Cat b= new Cat();
a.getName();
b.getName();

}

}


I have parent class Name animal which have two child class name Dog and Cat. They have the same method called getName. Now my question is why we use Animal type to create an object (here a and b) rather than Dog and Cat type. Both way, i get the same output.

Please answer me, if you can .

Return to JAVA Lobby

cron