Home > Java > javaTutorial > body text

Detailed introduction to the concept of polymorphism in Java and its principle implementation

黄舟
Release: 2017-04-13 09:57:58
Original
1832 people have browsed it

Polymorphism in JAVA is the embodiment of objects's multiple expressions. In Object-oriented, the most common polymorphism occurs when using a parent class's reference to refer to an object of a subclass. The following article mainly introduces it to you. Friends who need it can refer to

1. What is polymorphism?

1. The definition of polymorphism

refers to allowing objects of different types to respond to the same message. That is, the same message can adopt a variety of different behavior methods depending on the sending object (Sending a message is a function call)

2. The role of polymorphism

Eliminate the coupling relationship between types

3.Explanation of polymorphism

Modern Internet Novels Flooding, we can use it to give an example

One day you see multiple novels on your mobile phoneupdated at the same time, such as the Great Master, Lord Snow Eagle, Legend of the Dragon King... in Here we can describe it as follows:

Novel a=Great Master

Novel b=Snow Eagle Lord

Novel c=Legend of the Dragon King

What is shown here is polymorphism. The Great Master, Lord Snow Eagle, and Legend of the Dragon King are all subcategories of novels. We can reference different subcategories only through the parent category of novels. This is polymorphism - we Only at run time will you know the specific instance object pointed to by the reference variable

Of course, this understanding is far from enough. To get started with the understanding of polymorphism, you must Understand that it is "upward transformation"

In the above example, novel (XS) is the parent class, and the great master (DZZ), Snow Eagle Lord (XYLZ), and Dragon King Legend (LWCS) are all its subclasses. So , we define the following code

DZZ a=new DZZ();

You should not feel unfamiliar with this code. It is nothing more than instantiating a big master object. So for the following What about this code?

XS a=new DZZ();

Here we understand it this way, an XS type a is defined here, letting it point to the DZZ object Example. Since DZZ inherits from XS, DZZ can be automatically transformed upward to XS, so a can point to the DZZ instance object. There is a very big benefit in doing this. In inheritance, we know that the subclass is an extension of the parent class. It can provide more powerful functions than the parent class. If we define a parent class reference type that points to the subclass, then in addition to In addition to being able to reference the common features of the parent class, you can also use the powerful functions of the subclass

But upward transformation also has some shortcomings, that is, it will definitely lead to the loss of some methods and properties, and As a result we cannot obtain them. Therefore, the use of the parent class type can call all properties and methods defined in the parent class. It is beyond the reach of methods and properties that only exist in the subclass

public class XS {

    public void fun1() {
      System.out.println("XS中的fun1");
      fun2();
    }


  public void fun2() {
     System.out.println("XS中的fun2");    
  }
}
Copy after login
public class DZZ extends XS{

  /*
   * 子类重载父类方法
   * 父类中不存在该方法,向上转型后,父类是不能引用该方法的
   */
   public void fun1(String a) {
     System.out.println("DZZ中的fun1");
     fun2();
   }

   /*
    * 子类重写父类方法 
    * 调用必定使用这个方法
    */
   public void fun2() {
     System.out.println("DZZ中的fun2");
   }
}
Copy after login
public class DuoTaiTest {

   public static void main(String[] args) {
     XS a=new DZZ();
     a.fun1();
  }
}
output:
XS中的fun1
DZZ中的fun2
Copy after login

So for polymorphism We can summarize it as follows:
The parent class reference pointing to the subclass has been transformed upward. It can only access the methods and properties owned by the parent class, and methods that exist in the subclass but not in the parent class can only be accessed. , this reference cannot be used, despite overloading the method. If a subclass overrides some methods in the parent class, when calling these methods, it must use the methods defined in the subclass (dynamic connection, dynamic calling)

For oriented Object polymorphism is divided into compile-time polymorphism and run-time polymorphism. Edit-time polymorphism is static, which mainly refers to the overloading of methods. It is distinguished based on the different parameter lists. The function will become two different functions after editing, and there is no polymorphism at runtime. Runtime polymorphism is dynamic, and it is achieved through dynamic binding, which is what we call polymorphism.

2. Implementation of polymorphism

1. Implementation conditions

Inheritance was razor-sharp at the beginning. Prepared for the implementation of state. The subclass Child inherits the parent class Father. We can write a parent class type reference pointing to the subclass. This reference can handle both the parent class Father object and the subclass Child object. When the same message is sent to the subclass or the parent class When an object is used, the object will perform different behaviors according to the reference it belongs to. This is polymorphism. That is, polymorphism means that the same message causes different classes to make different responses

JavaThere are three necessary conditions to achieve polymorphism: inheritance, rewriting, and upward transformation

Inheritance: In polymorphism, there must be a subclass and a parent class that have an inheritance relationship.

Rewrite: The subclass redefines certain methods in the parent class, and the subclass will be called when these methods are called. Methods

向上转型:在多态中需要将子类的引用赋给父类对象,只有这样该引用才能够具备技能调用父类的方法和子类的方法

只有满足了上述三个条件,我们才能够在同一个继承结构中使用同一的逻辑实现代码处理不同的对象,从而达到执行不同的行为

对于Java而言,它多态的实现机制遵循一个原则:当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法

2.实现形式

继承

public class XS {

      private String name;

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public XS() {

    }

    public String drink() {
      return "你看的小说名字:"+getName();
    }

    public String toString() {
       return null;
    }


}
public class DZZ extends XS{


  public DZZ() {
    setName("DZZ");
  }

  public String drink() {
    return "你看的小说名字:"+getName();
  }

  public String toString() {

    return "小说名:"+getName();
  }
}
public class XYLZ extends XS{

  /**
   * 
   */
  public XYLZ() {
     setName("XYLZ");
  }

  public String drink() {
    return "你看的小说名字:"+getName();
  }

  public String toString() {

    return "小说名:"+getName();
  }
}   
public class DuoTaiTest {
    public static void main(String[] args) {
      XS [] xs=new XS[2];

      DZZ a=new DZZ();
      XYLZ b=new XYLZ();

      xs[0]=a;
      xs[1]=b;

      for(int i=0;i<2;i++) {
       System.out.println(xs[i].toString()+"::::"+xs[i].drink());
      }

      System.out.println("-------------------");
  }
}
ouput:
小说名:DZZ::::你看的小说名字:DZZ
小说名:XYLZ::::你看的小说名字:XYLZ
-------------------
Copy after login

在上面的代码中DZZ,XYLZ继承XS 并且重写了drink(),toString()方法,程序运行结果是调用子类中方法,输出DZZ,XYLZ的名称,这就是多态的表现。不同的对象可以执行相同的行为,但是他们都需要通过自己的实现方式来执行,这就要得益于向上转型了

我们都知道所有的类都继承自超类Object,toString()方法也是Object中方法,当我们这样写时:

Object o = new DZZ();
System.out.println(o.toString());

output:
小说名:DZZ
Copy after login

Object,XS,DZZ三者继承链关系是:DZZ—>XS—>Object。所以我们可以这样说:当子类重写父类的方法被调用时,只有对象继承链中的最末端的方法才会被调用。但是注意如果这样写:

Object o = new xs();

System.out.println(o.toString());

output:
null//因为DZZ并不存在于该对象继承链中
Copy after login

所以基于继承实现的多态可以总结如下:对于引用子类的父类类型,在处理该引用时,它适用于继承该父类的所有子类,子类对象的不同,对方法的实现也就不同,执行相同动作产生的行为也就不同。

如果父类是抽象类,那么子类必须要实现父类中所有的抽象方法,这样该父类所有的子类一定存在统一的对外接口,但其内部的具体实现可以各异。这样我们就可以使用顶层类提供的统一接口来处理该层次的方法。

The above is the detailed content of Detailed introduction to the concept of polymorphism in Java and its principle implementation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template