Home  >  Article  >  Java  >  Analysis of the definition and usage of polymorphism in Java

Analysis of the definition and usage of polymorphism in Java

黄舟
黄舟Original
2017-09-28 10:01:231850browse

This article mainly introduces the definition and usage of Java polymorphism. It analyzes the concept and functions of polymorphism in more detail as well as the related operating skills of Java definition and implementation of object-oriented polymorphism. Friends in need can refer to it

The examples in this article describe the definition and usage of Java polymorphism. Share it with everyone for your reference, the details are as follows:

Polymorphism is through:

1 interface and several different classes that implement the interface and cover the same method in the interface Reflected

2 The parent class and the implementation of several different subclasses that inherit the parent class and cover the same method in the parent class.

1. Basic concepts

Polymorphism: Send a message to an object and let the object decide what behavior to respond to. Dynamic method invocation is implemented by assigning the subclass object reference to the superclass object reference variable.

This mechanism of Java follows a principle: when a superclass object reference variable refers to a subclass object, the type of the referenced object rather than the type of the reference variable determines whose member method is called, but this is called The method must be defined in the super class, that is, the method is overridden by the subclass.

If a is a reference to class A, then a can point to an instance of class A, or to a subclass of class A.

If a is a reference to interface A, then a must point to an instance of a class that implements interface A.

2. Java polymorphism implementation mechanism

#SUN’s current JVM implementation mechanism, the reference of a class instance points to a handle (handle) pointer, this handle is a pair of pointers:

One pointer points to a table. In fact, this table also has two pointers (one pointer points to a method table containing objects, and the other points to a class object, indicating that The type to which the object belongs);

Another pointer points to a memory space allocated from the java heap.

3. Summary

#1. Dynamic method invocation is achieved by assigning the subclass object reference to the superclass object reference variable.


DerivedC c2=new DerivedC();
BaseClass a1= c2; //BaseClass 基类,DerivedC是继承自BaseClass的子类
a1.play(); //play()在BaseClass,DerivedC中均有定义,即子类覆写了该方法

Analysis:

1. Why can object instances of subclass types be overridden to superclass references?

Automatically realize upward transformation. Through this statement, the compiler automatically moves the subclass instance upwards and becomes the universal type BaseClass;

2, a.play()Will the method defined by the subclass or the parent class be executed?

Subclass. During runtime, the corresponding method will be obtained based on the actual type of the object reference a. That's why there's polymorphism. If a base class object reference is assigned to a different subclass object reference, it will show different behaviors when the method is executed.

When a1=c2, there are still two handles, a1 and c2, but a1 and c2 have the same data memory block and different function tables.

2. You cannot assign the parent class object reference to the subclass object reference variable


BaseClass a2=new BaseClass();
DerivedC c1=a2;//出错

In java, upward transformation is It is done automatically, but downward transformation is not. We need to define it ourselves and force it.

c1=(DerivedC)a2; Perform forced transformation, that is, downward transformation.

3. Remember a very simple yet complex rule , a type reference can only refer to methods and variables contained in the reference type itself.

You may say that this rule is wrong, because when the parent class reference points to the subclass object, the method of the subclass is finally executed.

In fact, this is not a contradiction. That is because late binding is used, and the subclass method is called according to the type during dynamic operation. And if this method of the subclass is not defined in the parent class, an error will occur.

For example, in addition to inheriting the functions defined in BaseClass, the DerivedC class also adds several functions (such as myFun())

Analysis:

When you use a parent class reference to point to a subclass, the jvm has actually used the type information generated by the compiler to adjust the conversion.

You can understand it this way, which is equivalent to setting functions that are not included in the parent class to invisible from the virtual function table. Note that it is possible that some function addresses in the virtual function table have been rewritten in the subclass, so the address of the virtual function item in the object virtual function table has been set to the address of the method body completed in the subclass.

4. Comparison of polymorphism between Java and C++

jvm’s solution to polymorphism support is almost the same as that in c++, except that there are many compilers in c++ It puts both type information and virtual function information in a virtual function table, but uses some technology to distinguish them.

Java separates type information and function information. After inheritance in Java, the subclass will reset its own virtual function table. The items in this virtual function table are composed of two parts. Virtual functions inherited from the parent class and subclass's own virtual functions.

Virtual function calls are indirectly called through the virtual function table, so polymorphism can be achieved. All functions in Java, except those declared as final, use late binding.

四. 1个行为,不同的对象,他们具体体现出来的方式不一样,

比如: 方法重载 overloading 以及 方法重写(覆盖)override


class Human{
void run(){输出 人在跑}
}
class Man extends Human{
void run(){输出 男人在跑}
}

这个时候,同是跑,不同的对象,不一样(这个是方法覆盖的例子)


class Test{
void out(String str){输出 str}
void out(int i){输出 i}
}

这个例子是方法重载,方法名相同,参数表不同

ok,明白了这些还不够,还用人在跑举例


Human ahuman=new Man();

这样我等于实例化了一个Man的对象,并声明了一个Human的引用,让它去指向Man这个对象

意思是说,把 Man这个对象当 Human看了.

比如去动物园,你看见了一个动物,不知道它是什么, “这是什么动物? ” “这是大熊猫! “

这2句话,就是最好的证明,因为不知道它是大熊猫,但知道它的父类是动物,所以,这个大熊猫对象,你把它当成其父类 动物看,这样子合情合理.这种方式下要注意 new Man();的确实例化了Man对象,所以ahuman.run()这个方法 输出的 是 “男人在跑 “如果在子类 Man下你 写了一些它独有的方法 比如 eat(),而Human没有这个方法,在调用eat方法时,一定要注意 强制类型转换 ((Man)ahuman).eat(),这样才可以…

对接口来说,情况是类似的…


package domatic;
//定义超类superA
class superA {
int i = 100;
void fun(int j) {
j = i;
System.out.println("This is superA");
}
}
// 定义superA的子类subB
class subB extends superA {
int m = 1;
void fun(int aa) {
System.out.println("This is subB");
}
}
// 定义superA的子类subC
class subC extends superA {
int n = 1;
void fun(int cc) {
System.out.println("This is subC");
}
}
class Test {
public static void main(String[] args) {
superA a = new superA();
subB b = new subB();
subC c = new subC();
a = b;
a.fun(100);
a = c;
a.fun(200);
}
}


/*
* 上述代码中subB和subC是超类superA的子类,我们在类Test中声明了3个引用变量a, b,
* c,通过将子类对象引用赋值给超类对象引用变量来实现动态方法调用 。也许有人会问:
* “为什么(1)和(2)不输出:This is superA” 。
* java的这种机制遵循一个原则:当超类对象引用变量引用子类对象时,
* 被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,
* 但是这个被调用的方法必须是在超类中定义过的,
* 也就是说被子类覆盖的方法 。
* 所以,不要被上例中(1)和(2)所迷惑,虽然写成a.fun(),但是由于(1)中的a被b赋值,
* 指向了子类subB的一个实例,因而(1)所调用的fun()实际上是子类subB的成员方法fun(),
* 它覆盖了超类superA的成员方法fun();同样(2)调用的是子类subC的成员方法fun() 。
* 另外,如果子类继承的超类是一个抽象类,虽然抽象类不能通过new操作符实例化,
* 但是可以创建抽象类的对象引用指向子类对象,以实现运行时多态性 。具体的实现方法同上例 。
* 不过,抽象类的子类必须覆盖实现超类中的所有的抽象方法,
* 否则子类必须被abstract修饰符修饰,当然也就不能被实例化了
*/

以上大多数是以子类覆盖父类的方法实现多态.下面是另一种实现多态的方法———–重写父类方法

1.JAVA里没有多继承,一个类之能有一个父类 。而继承的表现就是多态 。一个父类可以有多个子类,而在子类里可以重写父类的方法(例如方法print()),这样每个子类里重写的代码不一样,自然表现形式就不一样 。这样用父类的变量去引用不同的子类,在调用这个相同的方法print()的时候得到的结果和表现形式就不一样了,这就是多态,相同的消息(也就是调用相同的方法)会有不同的结果 。举例说明:


//父类
public class Father{
//父类有一个打孩子方法
public void hitChild(){
}
}
//子类1
public class Son1 extends Father{
//重写父类打孩子方法
public void hitChild(){
System.out.println("为什么打我?我做错什么了!");
}
}
//子类2
public class Son2 extends Father{
//重写父类打孩子方法
public void hitChild(){
System.out.println("我知道错了,别打了!");
}
}
//子类3
public class Son3 extends Father{
//重写父类打孩子方法
public void hitChild(){
System.out.println("我跑,你打不着!");
}
}
//测试类
public class Test{
public static void main(String args[]){
Father father;
father = new Son1();
father.hitChild();
father = new Son2();
father.hitChild();
father = new Son3();
father.hitChild();
}
}

都调用了相同的方法,出现了不同的结果!这就是多态的表现!

The above is the detailed content of Analysis of the definition and usage of polymorphism in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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