Studyon Minte9.com
Head First (Java)




Polymorphism



* Reference

	With polymorphism, the reference and the object can be different.

	%java
		
		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {

			Animal[] animals = new Animal[3];
			animals[0] = new Dog();
			animals[1] = new Cat();
			animals[2] = new Wolf();
			
			for(int i=0; i<animals.length; i++) {
			    animals[i].eat();
			    animals[i].roam();
			}
				/* Output:
					HamHam is eating
					HamHam is roaming
					Pussy is eating
					Pussy is roaming
					Danger is eating
					Danger is roaming
				*/
		    }
		}

		class Animal {
		    protected String name;
		    public Animal() {
		    }
		    
		    public void eat() {
			System.out.println(this.name + " is eating");
		    }
		    
		    public void roam() {
			System.out.println(this.name + " is roaming");
		    }
		}

		class Dog extends Animal {
		    public Dog() {
			this.name="HamHam";
		    }
		}

		class Cat extends Animal {
		    public Cat() {
			this.name="Pussy";
		    }
		}

		class Wolf extends Animal {
		    public Wolf() {
			this.name="Danger";
		    }
		}

	
* Arguments

	If you write code using polymorphic arguments, where you declare the method parameter as a 
	super-class type, you can pass in, any subclass object at runtime.

	%java

		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {

			Vet v = new Vet();
			Dog d = new Dog();
			Cat c = new Cat();
			v.giveShot(d);
			v.giveShot(c);
				// Output:
				// dog make noise
				// cat make noise
		    }
		}

		class Vet {
		    public void giveShot(Animal a) {
			a.makeNoise();
		    }
		}

		class Animal {
		    protected String name;
		    public Animal() {
		    }
		    public void makeNoise() {
			System.out.println(this.name + " make noise");
		    }
		}

		class Dog extends Animal {
		    public Dog() {
			this.name = "dog";
		    }
		}

		class Cat extends Animal {
		    public Cat() {
			this.name = "cat";
		    }
		}