Polymorphism vs Overriding vs Overloading

前端 未结 21 2778
北恋
北恋 2020-11-22 01:10

In terms of Java, when someone asks:

what is polymorphism?

Would overloading or overriding be

21条回答
  •  既然无缘
    2020-11-22 01:34

    Both overriding and overloading are used to achieve polymorphism.

    You could have a method in a class that is overridden in one or more subclasses. The method does different things depending on which class was used to instantiate an object.

        abstract class Beverage {
           boolean isAcceptableTemperature();
        }
    
        class Coffee extends Beverage {
           boolean isAcceptableTemperature() { 
               return temperature > 70;
           }
        }
    
        class Wine extends Beverage {
           boolean isAcceptableTemperature() { 
               return temperature < 10;
           }
        }
    

    You could also have a method that is overloaded with two or more sets of arguments. The method does different things based on the type(s) of argument(s) passed.

        class Server {
            public void pour (Coffee liquid) {
                new Cup().fillToTopWith(liquid);
            }
    
            public void pour (Wine liquid) {
                new WineGlass().fillHalfwayWith(liquid);
            }
    
            public void pour (Lemonade liquid, boolean ice) {
                Glass glass = new Glass();
                if (ice) {
                    glass.fillToTopWith(new Ice());
                }
                glass.fillToTopWith(liquid);
            }
        }
    

提交回复
热议问题