接口

接口内的方法自动会声明为public;成员变量会自动定义为public、static和final(编译时常量)。

一、Java的多重继承

使用接口:

  1. 为了向上转型为多个基类型
  2. 防止客户端创建该类的对象,并确保这仅仅是一个接口(与使用抽象类的效果相同)

二、通过继承来扩展接口


三、适配接口

策略模式


四、接口中的域

在接口中定义的域不能是“空final”,但可以被非常量表达式初始化。


五、接口与工厂

//: interfaces/Factories.java
import static net.mindview.util.Print.*;

interface Service {
  void method1();
  void method2();
}

interface ServiceFactory {
  Service getService();
}

class Implementation1 implements Service {
  Implementation1() {} // Package access
  public void method1() {print("Implementation1 method1");}
  public void method2() {print("Implementation1 method2");}
}   

class Implementation1Factory implements ServiceFactory {
  public Service getService() {
    return new Implementation1();
  }
}

class Implementation2 implements Service {
  Implementation2() {} // Package access
  public void method1() {print("Implementation2 method1");}
  public void method2() {print("Implementation2 method2");}
}

class Implementation2Factory implements ServiceFactory {
  public Service getService() {
    return new Implementation2();
  }
}   

public class Factories {
  public static void serviceConsumer(ServiceFactory fact) {
    Service s = fact.getService();
    s.method1();
    s.method2();
  }
  public static void main(String[] args) {
    serviceConsumer(new Implementation1Factory());
    // Implementations are completely interchangeable:
    serviceConsumer(new Implementation2Factory());
  }
} /* Output:
Implementation1 method1
Implementation1 method2
Implementation2 method1
Implementation2 method2
*///:~

接口和抽象类:

抽象类中的抽象方法(其前有abstract修饰)不能用private、static、synchronized、native访问修饰符修饰。原因如下:抽象方法没有方法体,是用来被继承的,所以不能用private修饰。
接口里的变量:只能是公共静态的常量(自动设为public static final)
1. 接口方法,访问权限必须是公共的 public(可省略不写)
2. 接口内只能有公共方法,不能存在成员变量
3. 接口内只能含有未被实现的方法,也叫抽象方法,但是abstract关键字可省略不写。
接口不是类,不能实例化一个接口,但是可以声明接口的变量来引用实现了接口的类对象。

局部内部类不能用public或者private访问修饰符修饰。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值