接口

本文介绍了接口的基本概念,包括如何编写接口、接口的特点及其在Java与C#中的不同之处。此外,还提供了一个打印机的例子,展示了如何通过接口实现不同类型的墨盒和纸张。
接口
1.如何编写接口?
[修饰符] interface 接口名 extends 父类接口1,父类接口2{
//常量定义//方法定义}

class 类名 extends父类名 implements 接口1,接口2 {
//类成员}


例子:
public interface UsbInterface
{
void service();
}


public class UDisk implements UsbInterface
{
public void service()
{
System.out.println("连接USB口,开始传输数据");
}
}


public class UsbFan implements UsbInterface
{
public void service()
{

System.out.println("连接usb,获得电流,风扇开始转动");
}
}


public class Test
{
//1.U盘
UsbInterface udisk=new Udisk();
udisk.service();
//2.usb风扇

UsbInterface uabfab=new UsbFan();
usbfan.service();
}


2.接口有那些特征?
(1)接口中没有构造方法
(2)接口中的方法都是全局抽象方法
(3)接口中的属性全是静态常量


3.C#接口与java接口的区别:
(1)java接口中通过extends来继承父接口,类通过implements实现接口;
C#中通过冒号“:”来实现这两个功能。
(2)java接口中可以定义静态常量和方法,C#接口中不允许包含任何静态成员。
(3)java接口中的成员变量都是常量,自动public static final 修饰 ;
C#接口中不允许存在成员变量,但可以有属性


4.接口的定义:接口是一种能力,接口是一种约定。
例子:

public interface Paper
{
//得到纸张的大小
public String getSize();
}

public interface Inkbox
{
//得到墨盒的yanse
public String getColor();
}

public class Printer
{
Inbox inkbox;//墨盒
Paper paper;//纸张

public void srtInbox(Inkbox inkbox)
{
inkbox=inkbox;
}
public void setPaper(Paper paper)
{
this.paper=paper;
}
public void print()
{
System.out.println("使用"+inkBox.getColor()+"墨盒"+paper.getSize()+"的纸上打印");
}
}


public class A4Paper implements Paper {

public String getSize() {
return "A4";
}

}


public class B5Paper implements Paper {

public String getSize() {
return "B5";
}

}

public class ColorInbox implements Inbox {

public String getColor() {

return "彩色";
}

}

public class GrayInkBox implements Inbox {

public String getColor() {

return "墨白";
}

}


public static void main(String[] args) {
// TODO Auto-generated method stub
// 定义打印机
Inbox inbox=null;
Paper paper=null;
Printer printer=new Printer();
inbox = new GrayInkBox();
paper=new A4Paper();
//使用黑白墨盒在A4纸上dayin
printer.setInbox(inbox);
printer.setPaper(paper);
printer.print();
//使用彩色墨盒在B5纸上打印
inbox=new ColorInbox();
paper=new B5Paper();
printer.setInbox(inbox);
printer.setPaper(paper);
printer.print();

//使用彩色墨盒在A4纸上打印
paper=new A4Paper();
printer.setPaper(paper);
printer.print();
}

}


5.接口不能实例化。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值