Java polymorphism (Dynamic binding)

Source: Internet
Author: User

Encapsulation creates new data types by merging features and behaviors, and "implementing shadowing" separates interfaces and implementations by "privatizing" the details. inheritance can allow for upward transformation, treating an object as its own type or its base class, but this must satisfy the "is a" relationship, while polymorphism eliminates the coupling between types. Allows a type to exhibit differences from other similar types as long as they are derived from the same base class. Polymorphism by separating what to do and how to do it, from another point of view the interface and the realization of separation. But the inherited upward transformation will narrowing the interface , so that the methods of the derived class extension cannot be used after they have been transformed upward.
Package jin.feng1; Class person{  void Print () {  System.out.println ();}//}public class Student extends person{public void SST () {} PU Blic static void Main (string[] args) {person  p1=new Student ();  P1.sst (); Compile error, cannot access  p1.print ();}}

Late binding (polymorphic mechanism): both derived and base classes have the same method (overwrite), and are called without knowing which method to call, whether to call a base class or a method of a derived classdynamic binding is for an upward-transformed object, and if there is no upward transformation, which method the call is called. For an upward-transformed object invocation method, the method it calls is definitely the method provided by the object type upward transformation, that is, the person type only provides the print () method, so its optional method is the base class non-private method, if it is called the method is the base class only (subclass does not overwrite), The base class method is called, and the corresponding subclass method is called if the calling method child class overrides it. associating a method call with the same method body is called a binding. Binding before the program executes is called early binding. late binding, which is binding at run time based on the type of the object. Late binding is also called dynamic binding or running is binding. In order to be able to determine the type of the object in operation, the appropriate method is called. This means that the compiler does not know the specific object type, but the method invocation mechanism can find the correct method body and call it. In addition to the static method and the final method in Java, all other methods are late-bound. It will happen automatically.  
Class person{  void Print () {System.out.println ("person");} void SST () {}} class Person1 extends person{  void print () {System.out.println ("Person1");}} class Person2 extends Pers on{  void print () {System.out.println ("Person2");}}  public class student{static void Tune (person p1) {  p1.print ();//subclass Overrides, the specific method is called according to the specific type} public static void Main (string[] args) {person  p1=new Person1 ();//p1 is the base class person type, and the subclass of the optional call does not overwrite the method SST () and the subclass Overrides methods print () p1.sst ();//subclasses are not covered, The base class Person P2=new Person2 () is called directly;   Tune (p1); Tune (p2);/}}

//outputPerson1Person2Although P1,P2 is a person type, it is derived from an upward transformation, so it is dynamically bound to the appropriate type during run time. and call the appropriate method. defect 1: "Overwrite of private method"overrides are for non-private methods, and in programs where the method of the base class is private, but the subclass also has a corresponding method name, the method is not overwritten, but a new method of the subclass.
public class student{private void Print () {System.out.println ("Student"), public static void main (string[] args) {  S Tudent p1=new Student1 ();  P1.print ();//seemingly dynamic binding, actually calling the private method in their own class. }} class Student1 extends student{  void print () {System.out.println ("Student1");}} Outputstudent Defect 2: Member variable and static method package Jin.feng1;class super{int field=0; int GetField () {return field;}} Class Sub extends Super{int field=1;int GetField () {return field;} int Getsuperfield () {return super.field;}} public class student{public  static void Main (string[] args) {  Super super1=new Sub ();  SYSTEM.OUT.PRINTLN ("Member Variable Access:" +super1.field+ "Method Access:" +super1.getfield ());  Sub Sub1=new Sub ();  System.out.println (Sub1.getfield () + "  " +sub1.getsuperfield ());}}

Outputmember Variable access: 0 method Access: 11 0add: If both the base class and the derived class define an identical member variable name and are not private, the subclass contains both variables, and if you need to access a variable with the same name as the base class, you need to Super.field, and if you access the same name method of the base class, you need Super.getfield () upward Transformation: Super super1=new Sub (); The member variable is accessed by the base class field, and the method accesses the GetField () method that accesses the derived class dynamically, then calls the derived class's field. What is the reason for discovering that member variable access operations are not dynamically bound? any member variable access operation will be parsed by the compiler and therefore not polymorphic. This will not happen in peacetime, because all member variables are generally private and cannot be accessed directly. defect 3, static methodbecause static methods belong to the entire class, they do not follow a specific object to transform the type. It can be said that it is not related to the object, so there is no dynamic binding.
Package jin.feng1;class static1{static void print () {System.out.println ("Static1 method");} void SS () { System.out.println ("Normal1 method");}} Class Static2 extends static1{static void print () {System.out.println ("Static2 Method"),} void SS () {SYSTEM.OUT.PRINTLN ( "Normal2 method");}} public class Staticdynmic{public static void Main (String args[]) {Static1 static1=new Static2 (); Static1.print (); Static1 . SS ();}}

OutputStatic1 MethodNormal2 MethodConstructors and PolymorphicThe constructor in Java differs from other methods, and the constructor is not polymorphic because it is a static method, but the static declaration is implicit, such as Construct c1=new Construct (); The constructor method is called , it does not require an object name to call it, so it is called before the object is created, and is the method of the class. The other method is to create the object first and then invoke it through the object.
Package jin.feng1; Class constructor11{  void Draw () {System.out.println ("Constructor11 Draw ()");}    Public Constructor11 () {   System.out.println ("Constructor11:before Draw ()");   Draw ();   System.out.println ("Constructor11:after Draw ()");  } } class Constructor12 extends constructor11{  private int radius=2;  Public Constructor12 () {   System.out.println ("Constructor12:before Draw ()");   Draw ();   System.out.println ("Constructor12:after Draw ()");  }  void Draw ()  {   System.out.println ("Constructor12+draw" +radius);}  } public class Constuctor22 {public  static void Main (string[] args)  {   new Constructor12 ();  

OutputConstructor11:before Draw ()Constructor12+draw 0Constructor11:after Draw ()Constructor12:before Draw ()Constructor12+draw 2Constructor12:after Draw ()when calling the base class construction method: When draw is first called, radius is 0 and has not been initialized. when calling a subclass construction method: When draw is called for the second time, RADIUS is 2, that is, in-class initializationThe class loads first. The storage space allocated to the object is initialized to 0. Then initialize the base class member variable, call the base class constructor, initialize the subclass member variable, and call the subclass constructor.

Java polymorphism (Dynamic binding)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.