Java programming ideas - detail Java polymorphism

Polymorphism is a technique that lets programmers "separate what changes from what doesn't." It can remove the coupling relationship between types, bringing programmers a faster program development process, better code organization, better extended programs, and easier code maintenance.


1. What is polymorphism

       Polymorphism not only improves the organization and readability of code, but also enables the creation of extensible programs (that is, programs that "grow" both when the project is initially created and as new functionality needs to be added). The reason why it can be extended is because the object type is forgotten by default in polymorphism, such as class Shap, whether it is Circle (circle), Square (square) or Triangle (triangle), it can be said to be a kind of Shape, that is, inheritance The "is-a" relationship that is often mentioned in , at this time, if you continue to add a Rhombus (diamond) class, it still satisfies this relationship, so when you perform an upward transformation, it can be said to be a Shape class, that is, ignoring the specific type, polymorphism Examples are as follows:

class Shape{
   public draw(){}
   public clear(){}
}
class Trangle extends Shape{
   //override parent class method
   public draw(){
      System.out.print("Draw Trangle");
   }
   public clear(){
     System.out.print("Clear Trangle");
   }
}
class Circle extends Shape{
   //override parent class method
   public draw(){
     System.out.print("Draw Circle ");
   }
   public clear(){
     System.out.print("Clear Circle ");
   }
}
//Can be extended Square, Rhombus...
public class Test{
   public static void main(String[] args){
     Shape[] shape = {new Trangle(), new Circle()};//Polymorphism, ignore the specific types of Trangle and Circle and regard them as Shape types together
     for(Shape s:shape){
        s.draw();
        s.clear();
     }
  }
}
out:
Draw Trangle
Clear Trangle
Draw Circle
Clear Circle

Second, the implementation mechanism - dynamic binding

       From the above example we can see that when the draw() and clear() methods are called with reference to s, it is not calling the methods of the base class, but calling the respective overridden methods in Trangle and Circle , which is exactly what we want , but how is it achieved? In fact, the compiler has no way of knowing, thanks to the binding at the time of method invocation .

1. What is binding

   Associating a method call with the same method body is called binding—that is, associating a Trangle with a method of its overridden base class.

2. Classification

   Binding is divided into early binding and late binding:

  • Early binding refers to binding before the program is executed, which is implemented by the compiler and linker. (This is the default binding in a procedural language )
  • Late binding refers to binding according to the type of the object at runtime, so it is also called dynamic binding or runtime binding .

      In order to perform late binding, there must be a mechanism to trigger, and this mechanism is the method invocation mechanism . In fact, the compiler does not know the object type all the time, but the method invocation mechanism can find the correct method body and add it. transfer. In reality, except for static and final (including private) methods in the Java language, other methods are late-binding , which means that late-binding occurs automatically in Java.

3. Why are static, final, and private modified methods in Java not late binding :

  • static method - A static method belongs to a class, so it is associated with the class from the moment it is created.
  • final methods - such methods cannot be overridden on the fly, so there is no choice ambiguity during invocation, so late binding is not required.
  • private methods - such methods are actually final methods, so the reason is the same as final.

Three, the defects of polymorphism

Polymorphism does not work for private methods, fields and static methods for the following reasons:

  • Private method : The private method is actually a method of final type , so it cannot be overridden, so only the private method of the parent class can be called.
  • Domain : It is not to mention that the domain of the same name of the parent class and the subclass are easily confused. In fact, the two domains have two independent memory blocks , so there is no problem that the domain can be overwritten, and the access to the domain is parsed by the compiler. , since it is a compiler resolution, it will not be dynamic binding, because dynamic binding is performed at execution time, so it is not polymorphic.
  • Static method : Polymorphism is actually an upward transformation of an object type, that is, the parent class reference points to the subclass object, but the class itself remains unchanged. The static method is actually directly associated with the class, not a single object, so the static method Not polymorphic .

**add another point**:

      Since there is an upward transformation, there must be a downward transformation , but since the methods of the subclass include not only all the base class methods, but also methods that the base class does not have, it is very likely that the method will be lost during the downward transformation. Failed, the specific examples are as follows:

class Useful{
   public void f(){}
   public void g(){}
}
class MoreUserful extends Useful{
   public void f(){}//Rewrite the parent class method
   public void g(){}//Override the parent class method
   public void u(){}//The subclass contains methods that the base class does not have
}
public class Test{
   public static void main(String[] args){
      Useful[] u={new Useful(),new MoreUseful()}; //Polymorphism (including upcasting)
      u[0].f();
      u[1].g();
      //To call the subclass method through the parent class, you need to downcast
      (MoreUseful)u[0].u();//Error ClassCastException
      (MoreUseful)u[1].u();//Downcast successfully!
   }
}

All casts are checked in Java , including casts of primitive types. - Runtime Type Identification (RTTI)

Exceptions encountered in polymorphism - ClassCastException class casting exceptions, which usually fail during downcasting.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325945195&siteId=291194637