What is polymorphism, what is it for, and how is it used?

前端 未结 28 2724
南笙
南笙 2020-11-21 07:08

What is polymorphism, what is it for, and how is it used?

28条回答
  •  既然无缘
    2020-11-21 07:55

    Polymorphism is the ability to use an object in a given class, where all components that make up the object are inherited by subclasses of the given class. This means that once this object is declared by a class, all subclasses below it (and thier subclasses, and so on until you reach the farthest/lowest subclass) inherit the object and it's components (makeup).

    Do remember that each class must be saved in separate files.

    The following code exemplifies Polymorphism:

    The SuperClass:

    public class Parent {
        //Define things that all classes share
        String maidenName;
        String familyTree;
    
        //Give the top class a default method
        public void speak(){
             System.out.println("We are all Parents");
        }
    }
    

    The father, a subclass:

    public class Father extends Parent{
        //Can use maidenName and familyTree here
        String name="Joe";
        String called="dad";
    
        //Give the top class a default method
        public void speak(){
            System.out.println("I am "+name+", the father.");
        }
    }
    

    The child, another subclass:

    public class Child extends Father {
        //Can use maidenName, familyTree, called and name here
    
        //Give the top class a default method
        public void speak(){
            System.out.println("Hi "+called+". What are we going to do today?");
        }
    }
    

    The execution method, references Parent class to start:

    public class Parenting{
        public static void main(String[] args) {
            Parent parents = new Parent();
            Parent parent = new Father();
            Parent child = new Child();
    
            parents.speak();
            parent.speak();
            child.speak();
        }
    }
    

    Note that each class needs to be declared in separate *.java files. The code should compile. Also notice that you can continually use maidenName and familyTree farther down. That is the concept of polymorphism. The concept of inheritance is also explored here, where one class is can be used or is further defined by a subclass.

    Hope this helps and makes it clear. I will post the results when I find a computer that I can use to verify the code. Thanks for the patience!

提交回复
热议问题