java接口用作类型_Java接口作为类型

接口定义了一个新的引用类型。可以使用接口类型来声明变量,在方法中声明参数类型,作为方法的返回类型等。

interface Shape { void draw(); } public class Main { // interface type as instance variable private Shape myShape; // interface type as parameter type for a constructor public Main(Shape s) { this.myShape = s; } // interface type as return type of a method public Shape getShape() { return this.myShape; } // interface type as parameter type for a method public void setShape(Shape s) { this.myShape = s; } public void letItSwim() { // interface type as a local variable Shape locaShape = null; locaShape = this.myShape; // interface variable can invoke methods // declared in the interface and the Object class locaShape.draw(); } }

接口类型的变量是指其类实现该接口的内存中的对象。使用接口类型的变量或直接使用接口名称来访问接口中声明的任何常量字段。

最好使用接口名访问接口的常量。使用接口类型的变量来调用接口中声明的任何方法。接口类型的变量可以调用java.lang.Object类的任何方法。

默认情况下,接口类型的实例或静态变量将初始化为null。

¥ 我要打赏   纠错/补充 收藏

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值