Core Java: Polymorphism

Polymorphism is one of the many compounds words used in tech. Polymorphism could be translate as “many forms “. In Java polymorphism is the principle of adapting many form which means that allow you to use resources from other classes without needing to know which class is using it. An example of polymorphism are override and overload.

Now let’s talk about Overridden methods, usually utilizes the @Override annotation in tops of its method. This methods are run time examples of polymorphism. To override a method first we need to use another object oriented principles in this case would be inheritance because we need to bring methods that are in another class or interfaces and change its behaviors.

Unlike Overridden methods, Overloaded methods doesn’t provide annotation. We could say that this methods are more useful than overridden ones, but each of them serve its purpose. Overloaded methods are compiler time examples of polymorphism and they can be re-structure , you can either change its behaviors, the return type or the quantity of parameters.

An brief example of how they are used:

public class Animal {
	
	public void sound() {
		System.out.println("sound");	
	}
	
}
public class Cat  extends Animal{
	
	@Override
	public void sound() {
		System.out.println("miaw miaw ");
	}
	
	
	public void sound(int quantity, int age) {
		System.out.println("miaws miaws");
	}

}
public class Dog  extends Animal{
	

	@Override
	public void sound() {
		
		System.out.println("waof waof");
	}
}

public class Shelter {

	public static void main(String[] args) {
		Cat cat = new Cat();

		dog.sound();
		cat.sound();
		cat.sound(1,3);
	}

}

You have a class named “Animal” and you will have a class named “Cat” that will extends Animal because all cats are animals, You can override the method “sound” from “Animal ” class since each animal have different sound then create an instance in the main class to execute the methods and see what will do.

Leave a comment

Design a site like this with WordPress.com
Get started