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

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

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

28条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 07:58

    Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. In this example that is written in Java, we have three type of vehicle. We create three different object and try to run their wheels method:

    public class PolymorphismExample {
    
        public static abstract class Vehicle
        {
            public int wheels(){
                return 0;
            }
        }
    
        public static class Bike extends Vehicle
        {
            @Override
            public int wheels()
            {
                return 2;
            }
        }
    
        public static class Car extends Vehicle
        {
            @Override
            public int wheels()
            {
                return 4;
            }
        }
    
        public static class Truck extends Vehicle
        {
            @Override
            public int wheels()
            {
                return 18;
            }
        }
    
        public static void main(String[] args)
        {
            Vehicle bike = new Bike();
            Vehicle car = new Car();
            Vehicle truck = new Truck();
    
            System.out.println("Bike has "+bike.wheels()+" wheels");
            System.out.println("Car has "+car.wheels()+" wheels");
            System.out.println("Truck has "+truck.wheels()+" wheels");
        }
    
    }
    

    The result is:

    For more information please visit https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java. I hope it helps.

提交回复
热议问题