java接口实例_Java 接口案例

1d59eeebaf97fd6eaa1c17d1fe83b76b.png

关于接口的定义,它根本没有提供任何具体实现,它允许创建者确定方法名,参数列表和返回类型,但是没有任何方法体。接口只提供了形式,而未提供任何具体实现。

接口 interface 关键字,可以在前面添加public关键字(仅限于该接口在于其同名文件中被定义),如果不添加public关键字,则它只具有包访问权限,这样它就只能在同一个包内可用。

51a0ac34a8e50b8f842e6d0d739d2b29.png

接口也可以包含域,但是这些域都是隐式的是 static 和 final 。

接口中可以显式的将方法声明为public的,即使你不这么做,它们也是public的。

看一下完整的代码:

interface Rodents{

int value = 10;

void play(int n);

void eat();

}

class Mouses implements Rodents {

@Override

public void play(int n) {

// TODO Auto-generated method stub

System.out.println(this + "PLAT()" + n);

}

@Override

public void eat() {

// TODO Auto-generated method stub

System.out.println(this + "EAT()");

}

}

class Gerbils implements Rodents {

@Override

public void play(int n) {

// TODO Auto-generated method stub

System.out.println(this + "PLAY()" + n);

}

@Override

public void eat() {

// TODO Auto-generated method stub

System.out.println(this + "EAT()");

}

}

class SmallRed extends Mouses {

public void play() {

System.out.println(this + "PLAY()");

}

public void play(int n) {

System.out.println(this + "PLAY(INT)");

}

public void eat() {

System.out.println(this + "EAT()");

}

}

class BigBlack extends Gerbils {

public void play() {

System.out.println(this + "PLAY()");

}

public void play(int n) {

System.out.println(this + "PLAY(INT)");

}

public void eat() {

System.out.println(this + "EAT()");

}

}

public class Demo03 {

static void tune(Rodents r) {

r.play(10);

r.eat();

System.out.println("------------------");

}

static void tuneAll(Rodents[] R) {

for (Rodents r : R) {

tune(r);

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Rodents[] rodents = {

new Mouses(),

new Gerbils(),

new SmallRed(),

new BigBlack()

};

tuneAll(rodents);

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值