Polymorphism vs Overriding vs Overloading

前端 未结 21 2787
北恋
北恋 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:29

    Polymorphism relates to the ability of a language to have different object treated uniformly by using a single interfaces; as such it is related to overriding, so the interface (or the base class) is polymorphic, the implementor is the object which overrides (two faces of the same medal)

    anyway, the difference between the two terms is better explained using other languages, such as c++: a polymorphic object in c++ behaves as the java counterpart if the base function is virtual, but if the method is not virtual the code jump is resolved statically, and the true type not checked at runtime so, polymorphism include the ability for an object to behave differently depending on the interface used to access it; let me make an example in pseudocode:

    class animal {
        public void makeRumor(){
            print("thump");
        }
    }
    class dog extends animal {
        public void makeRumor(){
            print("woff");
        }
    }
    
    animal a = new dog();
    dog b = new dog();
    
    a.makeRumor() -> prints thump
    b.makeRumor() -> prints woff
    

    (supposing that makeRumor is NOT virtual)

    java doesn't truly offer this level of polymorphism (called also object slicing).

    animal a = new dog(); dog b = new dog();

    a.makeRumor() -> prints thump
    b.makeRumor() -> prints woff
    

    on both case it will only print woff.. since a and b is refering to class dog

提交回复
热议问题