Java: Polymorphism
Polymorphism is mainly about polymorphic arrays, what these do is store a certain number of objects for derived classes.
You know before when we were declaring objects like this?
Class ObjName = new Class();
Well what this is doing is firstly setting Class as sort of a datatype, then it creates the reference variable 'ObjName', then finally it creates a new Class() instance.
However because Class is inherited from Base (its an example just go with it) we could declare it like this:
Base ObjName = new Class();
Right now your probably thinking "Yeah, well thats good and all, but it dosn't really help me", well this is where we can get started.
What we can do because Class is derived from Base is create a polymorphic array, we do this like so:
Base ArrayName[]= new Food[3];
We now have three pieces to out polymorphic array, we can set them to things like so:
ArrayName[0] = new Derived1(); ArrayName[1] = new Derived2(); ArrayName[2] = new Derived3();
Then we can do all kinds of things.
For example if we go back to last lesson we could use a for loop to output the 'IsFoodHot' function for every class in the array:
for(int x=0;x<3;++x){
ArrayName[x].IsFoodHot();
}
As you may have figured we can access functions and variables of objects in the array like so:
ArrayName[x].Function();
We can also create polymorphic arguments.
For example lets say we had the whole food program again, but we wanted someone to come along and say if they think that the food is cold, well what we could do is create a new class called consumer, and create a function which accepts a food object as a parameter:
class consumer{
void CustomerThoughts(Food varname){
varname.IsFoodHot();
}
};
For the sakes of this lesson we are just going to say the customer thinks the same as the generalised opinion.
Now we can call this from main:
consumer Bob = new consumer(); Food Object = new Food(); Bob.CustomerThoughts(Object);
At the moment this would output the food is hot or cold (as appropriate), but what we can also do is pass one of the derived classes as the food object.
For example the sandwich:
Food Object = new Sandwich();
Now its going to output the food is cold, (because we specified the sandwich class to do this).
Our full code for this would be something like this:
class Food{
private boolean FoodHot;
void MakeFoodHot(){
FoodHot = true;
}
void MakeFoodCold(){
FoodHot = false;
}
void IsFoodHot(){
if(FoodHot==true){
System.out.println("The food is hot!");
} else if(FoodHot==false){
System.out.println("The food is cold..");
} else {
System.out.println("Unspecified...");
}
}
};
class consumer{
void CustomerThoughts(Food varname){
varname.IsFoodHot();
}
};
class Sandwich extends Food{
void IsFoodHot(){
System.out.println("The food is cold!");
}
};
public class Main {
public static void main(String[] args) {
consumer Bob = new consumer();
Food Object = new Food();
Bob.CustomerThoughts(Object);
Object.MakeFoodHot();
Bob.CustomerThoughts(Object);
}
}
Back to Java

