mu_tou_man

导航

 

接口定义:

  [修饰符] interface 接口名 [extends 父接口名列表]

  {

    [public] [static] [final] 常量;
    [public] [abstract] 方法;
  }

1 public interface CalInterface 
2 {
3     final float PI=3.14159f;//定义用于表示圆周率的常量PI
4     float getArea(float r);//定义一个用于计算面积的方法getArea()
5     float getCircumference(float r);//定义一个用于计算周长的方法   getCircumference()
6 }

第一:既然有了抽象类,为什么还要接口?

  因为一个类只能继承一个父类,但是却可以实现多个接口。

第二:接口特性:

  1. 接口不是类,不能用new运算符来进行实例化
  2. 能声明接口变量,但是前提是该变量必须引用实现了该接口的类对象  例如:
    Comparable x;
    x=new Employee();
    public class Employee implements Comparable<Employee> 
    {
    
      ............  
    }

     

  3. 可以用instanceof 检查一个对象是否实现了某个接口
    if(anObject instanceof Comparable)
    {
      ........  
    }

     

  4. 接口也可以被继承,例如
    1 public interface Moveable
    2 {
    3     void move(double x,double y);
    4 }
    5 
    6 public interface Powered extends Moveable
    7 {
    8     void milesPer();  
    9 }

     

  5. 接口定义中不能有实例域和静态方法,但是可以包含常量,并且一个类可以实现多个接口
    public class Employee implements Comparable<Employee>,Callable

     

posted on 2015-06-04 15:50  mu_tou_man  阅读(187)  评论(0编辑  收藏  举报