Which method will be called? about Overriding and Overloading in Java

Categories: Java; Tagged with: ; @ May 13th, 2012 15:02

Here are two class: Animal and Dog, Dog extends from Animal:

package scjp.liguoliang.com;

public class Animal {
	
	private String type = "Dog";
	public String name = "Animal";
	
	public String getType() {
		return type;
	}
	
	public void eat() {
		System.out.println(name + ", Animal eat...");
	}
}
package scjp.liguoliang.com;

public class Dog extends Animal {
	
	private String type = "Dog";
	public String name = "Dog";
	
	
	public String getType() {
		return type;
	}
	
	public void eat() {
		System.out.println(name + ", Dog eat...");
	}
}

And here is the test codes:

	public static void main(String[] args) {
		Dog dog = new Dog();
		Animal animalDog = new Dog(); // New dog, but type is Animal.
		
		System.out.println(dog.name);
		System.out.println(dog.getType());
		dog.eat();
		
		System.out.println(animalDog.name);
		System.out.println(animalDog.getType());
		animalDog.eat();
		
		
		System.out.println("\nWe are going to test overloading:");
		OverLoadingTest overLoadingTest = new OverLoadingTest();
		overLoadingTest.testEat(animalDog);
		overLoadingTest.testEat(dog);
	}
	
	
	public void testEat(Animal animal) {
		System.out.println("Test Animal eat");
	}
	
	public void testEat(Dog dog) {
		System.out.println("Test Dog eat");
	}

Here is the output:

Dog
Dog
Dog, Dog eat...
Animal // Get the property by reference Type, so print the name of ‘Animal’
Dog // Polymorphism, call the method of the instance in run time;
Dog, Dog eat...

We are going to test overloading:
Test Animal eat // Compiler will decide which method will be called by reference type when compiling. 
Test Dog eat

In summary:

1. overriding: Polymorphism is for instance method, so  an animal type reference to a dog Object will call dog’s method; but for properties, will use animals.

2. overloading: which method will be called has been determined when compiling by the reference type.

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.