Polymorphism in Java

Source: Internet
Author: User

  1. The subclass and the parent class define exactly the same fields and methods, and what will happen. Run the following code to see what kind of results will appear.
     Public classParentchildtest { Public Static voidMain (string[] args) {Parent parent=NewParent ();        Parent.printvalue (); Child Child=NewChild ();                Child.printvalue (); Parent=Child ;                Parent.printvalue (); Parent.myvalue++;                Parent.printvalue (); ((child) parent). MyValue++;            Parent.printvalue (); }}classparent{ Public intmyvalue=100;  Public voidPrintvalue () {System.out.println ("Parent.printvalue (), myvalue=" +myvalue); }}classChildextendsparent{ Public intmyvalue=200;  Public voidPrintvalue () {System.out.println ("Child.printvalue (), myvalue=" +myvalue); }}

    Program:

  2. Program cause Analysis: When a subclass has the same method as the parent class, and when a parent class variable refers to a subclass object, which method is called, determined by the object's own "true" type, that is, the object is a subtype, it calls the method of the subtype, it is the parent type, and it invokes the method of the parent type.
  3. For polymorphism, it can be summed up as:

    One, a reference to the child class using the parent class type;

    Second, the reference can only invoke methods and variables defined in the parent class;

    Thirdly, if a method in the parent class is overridden in a subclass, the method in the subclass is called when the method is called; (dynamic connection, dynamic invocation)

    variables cannot be overridden (overwritten),the concept of "overriding" is only for methods, and if a variable in the parent class is "overridden" in a subclass, an error is made at compile time.

Polymorphism in Java

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.