Java reference types have two types: one is a compile-time type and the other is a run-time type. The compile-time type is determined by the type used when the variable was declared, and the run-time type is determined by the object actually assigned to the variable. If the compile-time type and the run-time type are inconsistent, so-called polymorphism may occur.
public class BaseClass { public int book = 6; public void base() { System.out.println("父类中的普通方法"); } public void text() { System.out.println("父类中被覆盖的方法"); } }
public class subClass extends BaseClass{ public String book ="java"; public void text() { System.out.println("子类中覆盖父类的方法"); } public void sub() { System.out.println("子类中的普通方法"); } public static void main(String[] args) { //下面编译时类型和运行时类型完全一样,所以不存在多态 BaseClass bc = new BaseClass(); System.out.println(bc.book); //下面两次调用的是BaseClass的方法 bc.text(); bc.base(); subClass sc = new subClass(); System.out.println(sc.book); //下面调用的是subClass类的方法 sc.sub(); sc.text(); //下面编译时类型与运行时类型是不一样的,就是所谓的多态 BaseClass bs = new subClass(); System.out.println(bs.book); bs.text(); bs.base(); //bs.sub(); //bs是父类的类型,他访问的是父类的shi'li'bian'liang } }
Three variables are created in the main() method of the above program. The first two reference variables, their compile-time type and run-time type are exactly the same, so their member variables and members are called The method is very normal, but the compile-time type of the third variable is inconsistent with the run-time type. When the text method of this reference variable is called, the method is defined in the parent class and overridden in the subclass. The actual method is executed. It is a method that overrides the parent class in the subclass.
Java allows a subclass object to be directly assigned to a reference variable of a parent class without any type conversion, or is called upward conversion. The upward conversion is automatically completed by the system.
When the method that refers to a variable is called at runtime, its method behavior always shows the behavioral characteristics of the subclass, not the behavioral characteristics of the parent class. This may occur: the same type of variable does not call the same method. One way is to present different behavioral characteristics instead of the behavioral characteristics of the parent class. This is polymorphism.
Unlike methods, instance variables of objects do not have polymorphism.
结果: 6 父类中被覆盖的方法 父类中的普通方法 java 子类中的普通方法 子类中覆盖父类的方法 6 子类中覆盖父类的方法 父类中的普通方法
The above is the detailed content of A supplement to polymorphism in Java. For more information, please follow other related articles on the PHP Chinese website!