JAVA - Interface

文章讲述了Java中的接口概念,强调接口作为规则的抽象性,属性为静态,行为是抽象方法。类通过`implements`关键字实现接口,文中以Computer类实现USBSupply接口,并与Light类交互为例,展示了如何使用接口进行方法调用。
摘要由CSDN通过智能技术生成

所谓的接口呢,其实就是规则,基本语法为: interface 接口名称 { 规则属性,规则的行为 }

接口其实都是抽象的,规则的属性必须为固定的,而且不能够修改。

属性和行为的访问权限必须是public.

属性应该是静态的,行为应该是抽象的

接口和类是两个层面的东西,接口可以继承其他的接口,类的对象需要遵循接口,在java中

,这个遵循,称之为实现(implements),类需要实现接口,而且可以实现多个接口。

​
public class InterfaceTest {
    public static void main(String[] args){

        Computer c = new Computer();
        Light light1 = new Light();
        c.usb1 = light1;

        Light light2 = new Light();
        c.usb2=light2;

        c.USBSupply();

    }

}

interface USBInterface{

}

interface USBSupply extends USBInterface{
    public void USBSupply();
}

interface USBReceived extends USBInterface{
    public void USBReceived();
}

class Computer implements USBSupply{
    USBReceived usb1;
    USBReceived usb2;
    public void USBSupply() {
        System.out.println("computer supply power...");
        usb1.USBReceived();
        usb2.USBReceived();
    }
}

class Light implements USBReceived{
    public void USBReceived() {
        System.out.println("Light received power...");
    }
}

​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值