Java 接口和实现:OnOff 接口示例

本文将演示如何使用 Java 接口和类实现来定义和使用功能。我们将创建一个名为 OnOff 的接口,它定义了 on()off() 方法,然后创建两个类 ComputerLamp 来实现该接口。

代码示例

public class HelloWorld {

    public interface OnOff {
        void on();
        void off();
    }
    
    public class Computer implements OnOff {
        public Computer() {
            
        }
        
        public void on() {
            System.out.println('on');
        }
        
        public void off() {
            System.out.println('off');
        }
    }
    
    public class Lamp implements OnOff {
        public Lamp() {
            
        }
        
        public void on() {
            System.out.println('on');
        }
        
        public void off() {
            System.out.println('off');
        }
    }
    
    public static void main(String[] args) {
        HelloWorld helloWorld = new HelloWorld();
        Computer hp = helloWorld.new Computer();
        hp.on();
        hp.off();
        
        Lamp lamp = helloWorld.new Lamp();
        lamp.on();
        lamp.off();
    }
}

解释

  1. 定义接口 OnOff

    • 接口使用 interface 关键字定义,并定义了两个方法 on()off(),这两个方法没有实现。
  2. 实现接口 ComputerLamp

    • ComputerLamp 类使用 implements 关键字实现 OnOff 接口,并分别实现了 on()off() 方法。
  3. main 方法中使用实现类

    • 创建 ComputerLamp 对象,并调用它们的 on()off() 方法。

总结

该示例展示了如何使用 Java 接口和类实现来定义和使用功能,并通过 OnOff 接口和 ComputerLamp 类演示了接口的使用方法。

Java 接口和实现:OnOff 接口示例

原文地址: https://www.cveoy.top/t/topic/H2A 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录