About the understanding of dynamic binding

Source: Internet
Author: User

When you have a function with the same name in a subclass and a parent class, if you generate an object of a subclass and call the function in the object of the subclass, what is the function of the call? For example

class Base{
int i=47;
int f(){
return g();
}
int g(){
return i;
}

class Dervied extends Base{
int i=27;
int g(){ file://override父类里面的方法
return i;
}
}
public class test {
public static void main (String[] args)
{
Derived d = new Derived(); //生成Derived的对象
System.out.println(d.f());
// d.f() === Derived.f(d);
}
}

D.F () is equivalent to = = Object D calls the parent class F () function, the F () function will call return g () This sentence, this time is in the call who G ()?

This time need dynamic binding Binding, so-called dynamic binding, popular is that the object in the call method can be judged by their own method or the method of the parent class method, in the end how to judge? I don't think it's a good idea, so it's just a popular explanation:

That is, the method that invokes the inside of the class where the current object resides:

If object D is generated from the current subclass dervied, then whenever it is called G (), it is called the G () function in the subclass derived without invoking the G () function in the parent base. I think this is the key to Java polymorphism.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.