There are actually two kinds of polymorphism:
1. Polymorphism of the method:
1.1 Method Overloading: The same method name, which performs different methods depending on the type and number of parameters passed in
1.2 Method Overwrite: The same method name, depending on the sub-class to implement different functions
2. Object polymorphism: Refers to the inheritance of the class, and the child and parent classes are converted to each other
1.1 Upward Transformation (auto-complete): Parent class Parent Class object = Subclass Instance
2.2 Downward transformation: Subclass Subclass Object = (parent Class) parent class instance;
Because the parent class can have more than one child class, and a subclass does not have too many parent classes, there is no compilation error in the upward transition, and a compile-time error may occur
Class a{public void print () {System.out.println (method in "a");}} Class B extends a{public void print () {System.out.println (method in "B");}} public class Test{public static void Main (String args[]) {A A =new a (); b b = (b) a;b.print ();}} /*exception in thread "main" java.lang.classcastexception:a cannot is cast to B at test.main (test.java:14) */
The above code has a class conversion exception, which refers to the exception caused by a forced downward transformation of two two non-relational class objects.
The use of the instanceof keyword, which is primarily to determine whether an object is an instance of a class:
Object instanceof class//Returns a Boolean
classa{ Public voidprint () {System.out.println ("Method in a"); }}classBextendsa{ Public voidprint () {System.out.println ("Method in B"); }} Public classtest{ Public Static voidMain (String args[]) {A A=NewB (); if(AinstanceofB) {b b=(b) B; } b.print (); }}
Note: Before a downward transformation occurs, it is important that the object's upward transformation occur first
Example: an upward transition instance
classa{ Public voidprint () {System.out.println ("Method in a"); }}classBextendsa{ Public voidprint () {System.out.println ("Method in B"); }} Public classtest{ Public Static voidMain (String args[]) {A A=NewB ();//Upward TransformationA.print ();//the method in B }}
polymorphic cases in Java