Polymorphism
essential means that if you have a child class of a parent class you can use
the child class anywhere you would use the parent class. For example you can declare variable with type
of parent class to objects of child class. Then when you call a method to that
variable it will call the method in the child class. When you run the method
the type of the variable doesn’t matter. What matters is the type object containing
the variables that’s going to run. So if you make a variable with a parent
class type, but it refers to a child class object. It’s going to run the code
in the child class.
Below
shows many examples of polymorphism. In the main method I made a tree object
and a plant object. Tree is a child class of plant. So we can declare a
variable type plant to a tree object. We can now call a method that is in both
the plant and tree class. When the method is called it will run the code in the
tree class. If you try and call a method not in the plant class using a tree
object it won’t work. This is shown in the comment below where shedLeaves is a
method only in the tree class.
public class App {
public static void main(String[] args) {
Plant
plant1 = new Plant();
Tree
tree = new Tree();
Plant
plant2 = tree;
plant2.grow();
tree.shedLeaves();
//plant2.shedLeaves();
doGrow(tree);
}
public static void doGrow(Plant plant){
plant.grow();
}
}
No comments:
Post a Comment