Polymorphism: ‘a state of having many shapes’ or ‘the capacity to take on different forms’. This same concept could be apply to object oriented programming languages like Java, it describes a language’s ability to process objects of various types and classes through a single, uniform interface.
For this example we are going to have two subclasses(Horse,Cat) and a parent class (Animal). Let's start by coding our parent class:
public class Animal{
public void sound(){
System.out.println("Animal is making a sound");
}
}
Then, let's code our Cat class:
public class Cat extends Animal{
@Override
public void sound(){
System.out.println("A cat sounds Meow, Meow");
}
}
Last, let's code our Horse class:
class Horse extends Animal{
@Override
public void sound(){
System.out.println("A horse sounds Neighhhh, Neighhh!");
}
}
Let's test our code:
public class TestClass {
public static void main(String [] args) {
Animal cat = new Cat();
Animal horse = new Horse();
cat.sound();
horse.sound();
}
}
Output:
A cat sounds Meow, Meow
A horse sounds Neighhhh, Neighhh!
No comments:
Post a Comment