Java Parent class object calls subclass Entity: method override vs. Dynamic Call

Source: Internet
Author: User

It is well known that Java handle and C + + Ponter instead of object, we are familiar with C + + 's parent class pointer call the subclass entity example, Then the Java handle is also possible?

here, Let me give you an example.

classfather{ public voidannounce () {System.out.println ("Father"); }}classChildextendsFather{@Override public voidannounce () {System.out.println ("child"); }} public classHello { public Static voidmain (string[] Args) {System.out.println ("Hello"); Father Father=Newchild ();    Father.announce (); }}

In this code, we assign the object of a subclass to the handle of the parent class, and then call the method that has been overloaded with the quilt class, and we get the following result:

Hello
Child

As we can see, using this parent class handle, we are actually calling the announce method of the Subclass. Knowing this feature can be a matter of fact.

Here we are going to introduce a concept: dynamic invocation

Dynamic linking means that when a method is implemented only in the parent class and not implemented in a subclass, we call the method in the parent class. And when a method is implemented in both the parent and subclass, we call the Subclass's method regardless of the type of Handle. however, This method must be defined in the parent class, otherwise it cannot be called by the parent class Handle.

It is also important to note that Java can be automatically transformed, that is, you can assign a class object to the parent class handle< but not automatically downward transformation, the method of downward transformation needs to be defined Manually.

Java Parent class object calls subclass Entity: method override vs. Dynamic Call

Related Article

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.