Java overloading and inheritance rules

后端 未结 3 1004
谎友^
谎友^ 2020-12-02 10:50

I\'ve been studying because I have an exam and I don\'t have many problems with most of Java but I stumbled upon a rule I can\'t explain. Here\'s a code fragment:

         


        
3条回答
  •  臣服心动
    2020-12-02 11:08

    I will clarified it in more simple way. See when you making sub class object with super class reference like here you did.

    Always one thing keep in your mind that when you call with super class reference, no matters object is of sub class it will go to the super class, check method with this name along with proper signature is there or not.

    now if it will find it, than it will check whether it is overridden?? if yes than it will go to the sub class method like here it went. another wise it will execute the same super class method.

    I can give you the example of it...just hide

    public int method(A a) {
            return 3;
        }
    

    method & check your answer you will get 1 2 1 2, why because it gives first priority to reference. because you overridden it & than calling it, so its giving 3..!! hope its big but easy to understand. Happy Learning

提交回复
热议问题