JAVA learning course 15th (polymorphism and its basic applications), java learning Polymorphism
Polymorphism:
The third feature of object-oriented definition: a function with the same name has multiple forms. For example, a function with a polymorphism has different parameter lists, and its existence is different, there is also a function that is placed in the parent class and in the subclass, and its existence is also different.
The object also has polymorphism.
Example: animals include pigs, cats, and dogs.
The cat object corresponds to the cat class.
Cat x = new CAT ();
At the same time, a cat is a type of animal, which can make a cat an animal.
Animal y = new CAT ();
Animal z = new dog ();
Animals are the parent class extracted from the group of dogs and cats.
The parent class references a subclass object.
I. Overview
// Object polymorphism // The manifestation of polymorphism, the parent type is directed to the self-object class animal {} class cat extends animal {} class dog extends animal {} public class Main {public static void main (String [] args) {// an object two forms animal small animal = new cat (); // a small animal creates an object through a cat. Animals are directed to/** cats and other things have the form of a cat, it also has the animal form. * This is the polymorphism of things * that is, an object corresponds to different types * the embodiment of polymorphism in code: * (parent class/interface) references point to the object of its subclass **/}}
Ii. Advantages of Polymorphism
It provides code scalability, and the code defined in the earlier stage can use the later content (only when animals are available)
The following code is used:
Abstract class animal {abstract void sing (); // call} class cat extends animal {void sing () {System. out. println ("");} void fun () // unique features of cat {System. out. println ("rat") ;}} class dog extends animal {void sing () {System. out. println ("Wangwang");} void fun () // unique function of the dog {System. out. println ("") ;}} class pig extends animal {void sing () {System. out. println ("hum");} void fun () {System. out. println ("") ;}} public class Main {public static void main (String [] args) {// a cat kitten = new cat (); kitten. sing (); // many cats cat two cats = new cat (); cat three cats = new cat (); catqun (two cats); catqun (three cats ); //.... // The embodiment of polymorphism, multiple animals dog 1 = new dog (); cat kitten 1 = new cat (); catqun (puppy 1 ); catqun (kitten 1); catqun (new pig ();} static void catqun (animal c) // animal c = new cat ()/dog () /pig (); {c. sing ();}}
Iii. Disadvantages and prerequisites of Polymorphism
1. disadvantages of polymorphism:
The content defined in the earlier stage cannot use the special content of the later stage subclass.
Static void catqun (animal c) {c. sing (); // c. fun ();-> there is no fun method in animal}
PS: Of course, the cat static void catqun (cat c) can be called directly, but we don't know how many species will appear in the future, with poor reusability.
2. Prerequisites for Polymorphism:
(1). It must be related, either inherited or implemented.
(2) overwrite (the parent class defines the function, and sub-classes are implemented. It is very troublesome to call a dog or a wolf. It's easy)
If we do not meet the requirements (2), we will use polymorphism if we do not have coverage. For example, if a dog looks at the house, it is normal, and a wolf looks at the house, there will be no problem.
The two prerequisites of polymorphism can be ensured to improve program scalability.
Iv. Transformation
Reflected in code:
Abstract class animal {abstract void sing (); // call} class cat extends animal {void sing () {System. out. println ("");} void fun () // unique features of cat {System. out. println ("rat") ;}} class dog extends animal {void sing () {System. out. println ("Wangwang");} void fun () // unique function of the dog {System. out. println ("") ;}} class pig extends animal {void sing () {System. out. println ("hum");} void fun () {System. out. println ("") ;}} public class Main {public static Void main (String [] args) {// previous command object/** cat kitten = new cat (); kitten. sing (); */animal a = new cat (); // The automatic type is increased. The cat object is promoted to an animal, similar to byte x = 3; int y = x;. sing (); // PS: Once a cat is promoted to an animal, its unique features cannot be accessed. // Professional statement, upward transformation. Objective: To restrict access to special functions // if the cat's special functions are still available, this object can be transformed down to cat c = (cat); // transform animal a to CAT cc. fun (); // The purpose of downward transformation is to use the special method in the subclass/* animal d = new animal (); * animal f = new dog (); * cat g = (cat) f; cat e = (cat) d; this type is not allowed. is a small animal a cat */}}
Note: For transformation, sub-class objects are being converted from beginning to end: the cat object will be transformed into an animal, and the cat object will be transformed into a cat
PS: Transition is purposeful
Exercise:
/** BLF and BLF2 story * BLF2 is the son of BLF **/class BLF {void function () {System. out. println ("write a program in C ++");} void speaks English () {System. out. println ("hello, world") ;}} class BLF2 extends BLF {void function () {System. out. println ("write programs in java");} void speaks Chinese () {System. out. println ("Hello, world") ;}} public class Main {public static void main (String [] args) {BLF x = new BLF2 (); // One day BLF2 impersonates BLFx. function (); // It can only be written in java, because BLF2 only uses javax. speaking English (); // yes. Make BLF2 speak English like BLF. // x. speaking Chinese (); // No, BLF2 has been transformed to BLF, and BLF2 features cannot be used to use BLF2 Z = (BLF2) x; // change to Z. speak Chinese ();}}
V. Type determination:
Instanceof usage: import java. lang. reflect. method; abstract class animal {abstract void sing ();} class cat extends animal {void sing () {System. out. println ("");} void fun () {System. out. println ("rat") ;}} class dog extends animal {void sing () {System. out. println ("Wang");} void fun () {System. out. println ("") ;}} public class Main {public static void main (String [] args) {animal BLF = new cat (); // The cat is transformed upwards to animal method1 (BLF); animal BLF2 = new dog (); // The cat is transformed upwards to animal method2 (BLF2 );} public static void method1 (animal a) {. sing (); //. fun (); we know that after the upward transformation, we will not be able to use the unique features of sub-classes // so if you want to use it, you have to transform cat c = (cat) a; c. fun (); // It is only possible, but if we pass on a dog} public static void method2 (animal a) {. sing (); if (a instanceof cat) // instancdof is used to determine the specific type of a // usually used for robustness judgment before the downward transformation {cat c = (cat) a; c. fun ();} else if (a instanceof dog) // Of course, a parent class has n multiple subclasses and cannot write n multiple if {dog c = (dog) a; c. fun ();} else if (a = null) {System. out. println ("type error ");}}}
Instaceof can be followed by a class or an interface, and it is only applicable to the judgment of referenced data types.
6. Characteristics of polymorphism members: (interview ......)
1. member variables
2. member functions
3. Static Functions
1. member variables
During compilation, see whether the referenced variable belongs to the class to call the member variable, has, compilation passed, no, compilation failed
{Why does the compilation fail?
If there is no sing method in the animal category
Animal c = new cat (); // promotes a cat to an animal
C. sing (); // The cat is now an animal, but the animal does not sing, so compilation fails}
When running, see whether the referenced variable belongs to the class to call the member variables and run the member variables in the class.
Put simply: for compilation and running, refer to the left side of the equal sign ("="), fu f = new zi ();
See the code: // This question will not appear in development, but will only appear during the interview...
Class fu {int num = 3;} class zi extends fu {int num = 4;} public class Main {public static void main (String [] args) {/* zi z = new zi (); * System. out. println (z. num); // common inheritance is to find the subclass first, and some subclasses directly overwrite ** // The polymorphism form fu f = new zi (); // The class is transformed to the parent class System. out. println (f. num); // 3 // member variable of the subclass to be printed, and then down-transform zi ff = (zi) f; System. out. println (ff. num); // 4 }}
2. member functions (non-static functions, important)
During compilation, refer to whether the referenced variable belongs to the class for calling functions, including, compiled, and not, and the compilation fails.
During running, check whether the called function exists in the class to which the object belongs and run the function in the class.
To put it simply: Compile to the left and run to the right.
(Non-static functions need to be called using objects, so the right side is displayed during running)
Class fu {void show () {System. out. println ("parent") ;}} class zi extends fu {void show () {System. out. println ("sub") ;}} public class Main {public static void main (String [] args) {fu f = new zi (); // hide the child type in the upward transition. show (); // print "child". If you annotate the subclass show, print the parent }}
3. Static functions (can be called directly using the class name, which is special)
In fact, there should be no static functions for Polymorphism of objects, but static functions can be called directly using class names to create objects to call static methods. This object is actually garbage
During compilation, refer to whether the referenced variable belongs to the class for calling static methods. If yes, the compilation passes, no, the compilation fails.
When running, see whether the referenced variable belongs to the class to call the function, and run the function in the class
Simply put: Compile and run both on the left.
Class fu {static void my () {System. out. println ("parent sta") ;}} class zi extends fu {static void my () {System. out. println ("sub-sta") ;}} public class Main {public static void main (String [] args) {fu f = new zi (); f. my (); // print "parent sta". If the my method in the parent class is deleted, compilation fails }}
Java Polymorphism
Because a is a C instance,
B B B = (B) a; this is to assign a to B, where B is only a declaration class,
A a = new C (); a is a c instance, so B. f1 (); first, call the C method. If the appropriate method is not found in C, the appropriate method can be found in B in the Declaration class.
In addition, class C extends B because C is a subclass of B, the method f1 called by the C object already overwrites the method f1 in B.
Java Polymorphism
Is it the concept of polymorphism?
Polymorphism allows different types of objects to respond to the same message. Polymorphism includes parameterized polymorphism and inclusion polymorphism. The polymorphism language has the advantages of flexibility, abstraction, behavior sharing, and code sharing, which effectively solves the same name problem of application functions.
There are two manifestations of polymorphism: overload and overwrite.
Overload occurs in the same category. It has nothing to do with what parent class subclass and inheritance.
Besides the function name, a function parameter (number and type) is used to identify a function ). That is to say, a class can have two or more functions called the same name and their parameters are different.
There is no relationship between them. They are different functions, but they may have similar functions. Therefore, they are named the same and increase readability!
Override occurs in the subclass! That is to say, if inheritance is required, overwriting occurs.
We know that we inherit a class, and we have all the methods of the parent class. If you are uncomfortable with the method and want to change the function, implement the function again in the subclass.
In this way, when this method is called, it is the process of executing the subclass. The function in the parent class is overwritten. (Of course, when overwriting, the function name and parameter must be exactly the same as that in the parent class. Otherwise, your method will not have any effect on the methods in the parent class, because the two are two functions and have no relationship)