[Java Basic] Polymorphism

Source: Internet
Author: User
Tags java reference

1. The Java reference variable has two types: one is the compile-time type, one is the runtime type, and the compile-time type is determined by the type used when declaring the variable, and the type of the runtime is determined by the object that is actually assigned to the variable. If the compile-time type and run-time type are inconsistent, the so-called polymorphism occurs;

2. The reference variable can only invoke the method of its compile-time type in the compile phase, but the runtime executes the method of its run-time type, which is the embodiment of the method polymorphism.

3, polymorphism is for the method, the property of the object is not polymorphic. When you access an object instance property by referencing a variable, the system always attempts to access the properties defined by the compile-time type, not the properties defined by the run-time type.


Example code:

Class Base {public int num = 9;public void base () {System.out.println ("base base ()");} public void info () {System.out.println ("Base info ()");}} Class Sub extends Base {public String num = "Sub class";p ublic void Sub () {System.out.println ("Sub Sub ()");} public void info () {System.out.println ("Sub info ()");}}  public class Main {public static void main (string[] args) {base BC = new Base ()//BC Compile-time type and run-time type are basebc.base ();//output: Base Base () bc.info ();//output: Base info () System.out.println (bc.num);//output: 9Sub sc = new Sub ();//SC compile-time type and run-time type are subsc.base (); /output: base base () Sc.info ();//output: Sub info () sc.sub ();//output: Sub Sub () System.out.println (sc.num);//output: Sub classbase polymorphism = new Sub ();//polymorphism compile-time type is base, run-time type is subpolymorphism.base ();//output: Base base () Polymorphism.info () ;//output: Sub info () System.out.println (polymorphism.num);//output: 9}}

[Java Basic] Polymorphism

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.