A detailed introduction to Java polymorphism

I. Overview

  • Polymorphism is the ability to have multiple different manifestations or forms of the same behavior.
  • Polymorphism is the concept of objects, not the concept of classes

Second, the format and use of polymorphism

1. Format

//格式一:
父类名称 对象名 = new 子类名称();
//格式二:
接口名称 对象名 = new 实现类();

2. Polymorphic code examples

I used the format 2 demo.
You can try the format 1 yourself. The format 2 is usually used more frequently.

//定义接口
interface Interface {
    
    
    //在接口中定义两个抽象方法
    void methodOne();
    void methodTwo();
}

//定义第一个实现类,重写接口中的两个抽象方法
class ImplOne implements Interface{
    
    
    @Override
    public void methodOne() {
    
    
        System.out.println("实现类ImplOne的methodOne方法");
    }
    @Override
    public void methodTwo() {
    
    
        System.out.println("实现类ImplOne的methodTwo方法");
    }
}

//定义第二个实现类,重写接口中的两个抽象方法
class ImplTwo implements Interface{
    
    
    @Override
    public void methodOne() {
    
    
        System.out.println("实现类ImplTwo的methodOne方法");
    }
    @Override
    public void methodTwo() {
    
    
        System.out.println("实现类ImplTwo的methodTwo方法");
    }
}

//创建测试类
public class Test {
    
    
    public static void main(String[] args) {
    
    
    
        //创建第一个多态对象
        Interface implOne = new ImplOne();
        //使用implOne调用两个方法
        implOne.methodOne();
        implOne.methodTwo();
        System.out.println("==========================");
        
        //创建第二个多态对象
        Interface implTwo = new ImplTwo();
        //使用implTwo调用两个方法
        implTwo.methodOne();
        implTwo.methodTwo();
    }
}

Run screenshot
Insert picture description here
【tips】

It can be seen that using polymorphism weJust care about what methods are in the interface, Don’t care about how other implementation classes are implemented,Provide uniform method calls for all implementation classes

Three, the upward and downward transformation of the object

1. Upward transformation

  • interface(Or parent class)Through the implementation class(Or subclass)De-instantiate, Is the upward transformation of the object, that is, the general polymorphic writing
  • Up-casting can be done automatically. And is safe, similar to the automatic conversion of data types from a small range to a large range

General format

接口名称 对象名 = new 实现类();

standard format

实现类名称 实现类对象名 = new 实现类();
接口名称 对象名 = (实现类)实现类对象名;

Interface and implementation class can be replaced with parent class and subclass at the same time

Code example

//定义接口
interface USB{
    
    
    void open();
    void close();
}
//定义第一个实现类
class Mouse implements USB{
    
    
    @Override
    public void open() {
    
    
        System.out.println("加载鼠标");
    }
    @Override
    public void close() {
    
    
        System.out.println("关闭鼠标");
    }
}
//定义第二个实现类
class Keyboard implements USB{
    
    
    @Override
    public void open() {
    
    
        System.out.println("加载键盘");
    }
    @Override
    public void close() {
    
    
        System.out.println("关闭键盘");
    }
}
//测试类
public class Test {
    
    
    public static void main(String[] args) {
    
    
    
		//向上转型 标准格式
        Mouse mouse = new Mouse();
        USB usbMouse = mouse;
        usbMouse.open();
        usbMouse.close();
        System.out.println("==========");

        //向上转型 一般格式
        USB usbKeyboard = new Keyboard();
        usbKeyboard.open();
        usbKeyboard.close();
    }
}

operation result
Insert picture description here

2. Downward transformation

  • Downcasting refers tointerface(Or parent class)Object, converted to implementation class(Subclass)Object, Must use cast
  • Not all parent objects can be converted to child objects.The conversion type must be unified, Otherwise it will report java.lang.ClassCastException(class conversion exception)
  • After using polymorphism, if you wantUse the member method of the implementation class, must be downcast

General format

接口名称 对象名A = new 实现类();
((实现类名称)对象名A) . 成员;

standard format

接口名称 对象名A = new 实现类();
实现类名称 对象名B = (实现类名称)对象名A;

Interface and implementation class can be replaced with parent class and subclass at the same time

Code example

Make a simple modification to the code of the upward transformation, add the test member method to the Mouse class

    public void test(){
    
    
        System.out.println("向下转型测试方法");
    }

Rewrite the test class

public class Test{
    
    
    public static void main(String[] args) {
    
    
        USB mouse = new Mouse();
        //标准格式 调用成员方法
        Mouse m = (Mouse)mouse;
        m.test();
        //一般格式 调用成员方法
        ((Mouse) mouse).test();
    }
}

operation result
Insert picture description here

3.instanceof keyword

  • The instanceof keyword can be usedDetermine whether a class of an object belongs to an interface, Can also be usedDetermine whether an instance object belongs to a certain class
  • The return value is in boolean
    format
对象名 instanceof 接口();

Code example

Modifications to the down-cast code test class

class Test{
    
    
    public static void main(String[] args) {
    
    
    
        USB mouse = new Mouse();
        
        //判断 mouse 所属的Mouse类是否实现了USB接口
        if (mouse instanceof USB){
    
    
            System.out.println("是的");
        }
        
        //判断 mouse 对象是否属于Mouse类
        if (mouse instanceof Mouse){
    
    
        	//结果为true,才会执行向下转型
        	//避免出现 java.lang.ClassCastException 错误
        	System.out.println("是的");
        	Mouse m = (Mouse)mouse;
        	m.test();
        }
    }
}

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44580492/article/details/106698878