1, Polymorphism overview
Object oriented programming has three characteristics: encapsulation, inheritance and polymorphism
Encapsulation is to hide the attributes and implementation details of the object, only disclose the interface, and control the access level of attribute reading and modification in the program; Inheritance is to derive a new class from an existing class. The new class can absorb the data properties and behaviors of the existing class and expand new capabilities; Today I will unveil the mystery of polymorphism.
1. Popular understanding: polymorphism is the ability of the same behavior to have multiple different forms or forms. Polymorphism is the same interface that uses different instances to perform different operations. As the name suggests, it means multiple forms, that is, a thing can have multiple forms. For example, black-and-white printers and color printers are printers, and the printed ones are color and black-and-white respectively;
For another example, for our computer, press F1
action | Interface | eject |
Press F1 | Flash | Help documentation for AS 3 |
Word | Word help | |
Windows | Windows help and support |
The same event will produce different results under different objects
2. Polymorphism is embodied in that the parent class reference variable can point to the child class object
3. Three necessary conditions for the existence of polymorphism: ① inheritance
② rewrite the method
③ the parent class reference points to the child class object Parent p = new Child();
(the definition and use format of polymorphism are as follows: Parent is the Parent class name, p is the variable name, and Child is the Child class name)
Note: when calling a method with a polymorphic parent reference variable, the overridden method of the subclass is called.
2, Characteristics of members in polymorphism
1. Characteristics of member functions in polymorphism:
① During compilation, refer to whether the class to which the reference type change belongs has a calling method. If it has been compiled, it will not pass if it has not been compiled
② At run time, refer to whether there is a called method in the class that actually generates the instance
2. The characteristics of member variables (non static) in polymorphism: reference the class to which the reference variable belongs regardless of compilation and operation
3. In polymorphism, the characteristics of static members (variables and functions): reference the class to which the reference variable belongs regardless of compilation and operation
instanceof keyword usage
instanceof is a binary operator in Java, similar to = =, >, < and other operators.
instanceof is a reserved keyword for Java. Its function is to test whether the object on its left is an instance of the class on its right, and return the boolean data type.
The following example creates the displayObjectClass() method to demonstrate the use of the Java instanceof keyword:
/* author by runoob.com Main.java */ import java.util.ArrayList; import java.util.Vector; public class Main { public static void main(String[] args) { Object testObject = new ArrayList(); displayObjectClass(testObject); } public static void displayObjectClass(Object o) { if (o instanceof Vector) System.out.println("Object is java.util.Vector Class"); else if (o instanceof ArrayList) System.out.println("Object is java.util.ArrayList Class"); else System.out.println("Object is " + o.getClass() + " Class"); } }
3, Polymorphic transformation
1. Upward transformation
Converting an object referenced by a subclass to a parent type is called an upward transformation. Generally speaking, it is to turn a child object into a parent object. Here, the parent class object can be an interface.
public class Animal { public void eat(){ System.out.println("animal eatting..."); } } public class Cat extends Animal{ public void eat(){ System.out.println("I eat fish"); } } public class Dog extends Animal{ public void eat(){ System.out.println("I eat bones"); } public void run(){ System.out.println("I can run"); } } public class Main { public static void main(String[] args) { Animal animal = new Cat(); //Upward transformation animal.eat(); animal = new Dog(); animal.eat(); } } //result: //I eat fish //I eat bones
This is the upward transformation, Animal animal = new Cat(); Converts the child object Cat to the parent object Animal. At this time, the method called by the Animal reference is a subclass method.
Problems needing attention in the process of transformation
- When transitioning up, methods defined separately by subclasses are lost. For example, for the run method defined in the Dog class above, when the animal reference points to the Dog class instance, the run method cannot be accessed. Animal Run() will report an error.
- A child class reference cannot point to a parent class object. Cat c = (Cat)new Animal(), this is not possible.
Benefits of upward transformation
- Reduce repetitive code and make the code concise.
- Improve system scalability.
Usage format: parent type variable name = new subclass type ();
Applicable scenario: when you don't need to face subclass types, you can complete the corresponding operations by improving extensibility or using the functions of the parent class.
2. Downward transformation
Corresponding to the upward transformation is the downward transformation. The downward transformation is to turn the parent object into a child object. Attention please! There are pits here
//Or the animal and cat dog above Animal a = new Cat(); Cat c = ((Cat) a); c.eat(); //I eat fish Dog d = ((Dog) a); d.eat(); // Error: Java lang.ClassCastException: com.chengfan.animal.Cat cannot be cast to com.chengfan.animal.Dog Animal a1 = new Animal(); Cat c1 = ((Cat) a1); c1.eat(); // Error: Java lang.ClassCastException: com.chengfan.animal.Animal cannot be cast to com.chengfan.animal.Cat
Why doesn't the first code report an error? As you know, because a itself is a Cat object, it can naturally be transformed into Cat, and it can't be transformed into Dog. Have you ever seen a Dog suddenly become a Cat?
a1 is an Animal object, and it cannot be transformed downward into any subclass object. For example, when you go to Archaeology and find a new creature, you know it is an Animal, but you can't directly say, ah, it's a cat or a dog.
Precautions for downward transformation
- The premise of downward transformation is that the parent object points to the child object (that is, it must be transformed upward before downward transformation)
-
Downward transformation can only be transformed into this kind of object (cats can't become dogs).
Usage format: subclass type variable name = (subclass type) variable of parent type;
Applicable scenario: when subclass specific functions are to be used.
virtual function
Virtual functions exist for polymorphism.
In fact, there is no concept of virtual function in Java. Its ordinary function is equivalent to the virtual function of C + +. Dynamic binding is the default behavior of Java. If you do not want a function in Java to have virtual function characteristics, you can add the final keyword to become a non virtual function.
4, Implementation of polymorphism
1. Override: subclasses can inherit the methods in the parent class without rewriting the same methods. However, sometimes subclasses do not want to inherit the methods of the parent class intact, but want to make certain modifications, which requires method rewriting. Method overrides are also called method overrides.
Rewriting is a subclass's rewriting of the implementation process of the accessible methods of the parent class, and the return value and formal parameters cannot be changed. That is, the shell remains unchanged and the core is rewritten!
The advantage of rewriting is that subclasses can define their own behavior as needed. That is, subclasses can implement parent class methods as needed.
A rewritten method cannot throw a new check exception or an exception that is broader than the declaration of the rewritten method.
2. Interface:
① The most representative interface in life is the socket. For example, a three connector plug can be connected to a three hole socket, because each country has its own interface rules. It may not be possible to go abroad, because of the interface types defined by foreign countries.
② The interface in java is similar to the interface in life. It is a collection of method features, but there is no method implementation. See another blog about interfaces I wrote
3. Abstract classes and abstract methods
In the object-oriented concept, all objects are described by classes, but conversely, not all classes are used to describe objects. If a class does not contain enough information to describe a specific object, such a class is an abstract class.
5, Polymorphic instance
public class TestPolymorphism { public static void animalSaySomething(Animals an) { an.saySomething(); if(an instanceof Cat) { //Judge whether the formal parameter an is the same as cat Cat cat=(Cat)an; //Strongly convert an to cat cat.show(); } } public static void main(String[] args) { Dog dog =new Dog(); Cat cat =new Cat(); Bird bird =new Bird(); animalSaySomething(dog); //Formal parameter name (argument); animalSaySomething(cat); animalSaySomething(bird); } } class Animals{ public void saySomething() { System.out.println("Ha ha ha ha ha ha ha"); } } class Dog extends Animals { public void saySomething() { System.out.println("Hey, hey, hey, hey"); } } class Cat extends Animals{ public void saySomething() { System.out.println("Roar, roar, roar"); } public void show() { System.out.println("Ah, ah, ah"); } } class Bird extends Animals{ public void saySomething() { System.out.println("Hee hee hee"); } }
Ha ha ha ha ha ha ha Hey, hey, hey, hey Roar, roar, roar Ah, ah, ah Hee hee hee
6, Advantages of polymorphism
1. Eliminate coupling between types
2. Replaceability
3. Extensibility
4. Interface
5. flexibility
6. Simplification