Welcome to the hair loss space where four years of IT dreams look back

java polymorphic actual combat analysis

Understanding of java polymorphism

Core understanding: different objects implement the same interface to complete different behaviors. Text example: Laptops have USB ports, and both the mouse and keyboard can be connected to the computer through the USB ports, so mouse clicks and keyboard input here are the manifestations of polymorphism.

Programming ideas

1. First complete the programming of the USB interface. —> Corresponding to the interface in the framework
2. The keyboard and mouse complete different behaviors (methods) through the implements USB interface. —>Corresponding to the serviceImp
3. The computer controls and completes the behavior of the keyboard and mouse. —>Corresponding to the controller in the frame
4. Print the log. —>log

Upload code

1. Write the USB interface class 代码片.

/**
 * USB接口类
 * @author yqq
 */
public interface Usb {
    
    
    //插入usb
    void open();
    //拔出usb
    void close();
}

/**
 * 鼠标类 implements USB 来完成鼠标的行为
 * @author yqq
 */
public class Mouse implements Usb {
    
    

    public void open() {
    
    
        System.out.println("鼠标插入");
    }

    public void close() {
    
    
        System.out.println("鼠标拔出");
    }

    public void getClick(){
    
    
        System.out.println("鼠标点击");
    }
}

/**
 * 键盘类  implements USB 完成键盘的行为
 * @author yqq
 */
public class Keyboard implements Usb{
    
    
    public void open() {
    
    
        System.out.println("键盘打开");
    }

    public void close() {
    
    
        System.out.println("键盘关闭");

    }

    public void getClick(){
    
    
        System.out.println("键盘输入");
    }
}

/**
 * 电脑类 控制鼠标和键盘完成不同的行为
 */
public class Computer {
    
    
    public void open(){
    
    
        System.out.println("笔记本开机");
    }
    public void close(){
    
    
        System.out.println("笔记本关机");
    }
    //定义笔记本接入USB接口  usb作为形参
    public void getUsb(Usb usb){
    
    
        usb.open();
        if (usb instanceof Mouse){
    
    
            Mouse mouse = (Mouse) usb;
            mouse.getClick();
        }else if (usb instanceof Keyboard){
    
    
            Keyboard keyboard = (Keyboard) usb;
            keyboard.getClick();
        }
    }
}

/**
 * oop多态测试类
 * @author yqq
 */
public class Test {
    
    
    public static void main(String[] args) {
    
    
        Computer computer = new Computer();
        computer.open();
        Mouse mouse = new Mouse();
        computer.getUsb(mouse);
        mouse.close();
        Keyboard keyboard = new Keyboard();
        computer.getUsb(keyboard);
        keyboard.close();
        computer.close();
    }
}

2. Execute the main method and print the log.


笔记本开机
鼠标插入
鼠标点击
鼠标拔出
键盘打开
键盘输入
键盘关闭
笔记本关机

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/weixin_42025953/article/details/114195410