Java 接口 interface implements

接口定义了一系列的抽象方法和常量,形成一个属性集合。

接口定义完成后任何类都可以实现接口,而且一个类可以实现多个接口。

实现接口的类必须实现接口中定义的抽象方法,具体实现细节由类自己定义。可以说接口定义了类的框架,它实际上是一种完全的抽象类。

接口的定义格式:

修饰符 interface 接口名 {
    // 声明变量
    类型 变量名;

    // 声明方法
    返回值类型 方法名(参数);
}

接口定义注意一下几点:

  1. 接口的修饰符只能为默认的(无修饰符)或者public。当修饰符为默认时,接口是包可见的,在几口所在的包之外的类不能使用接口。修饰符为public时,任何类都可以使用该接口。
  2. 接口的名字应该符合Java的标识符规定。
  3. 接口内可以声明变量,接口内的变量被自动设置为共有的(public)、静态的(static)、最终的(final)。
  4. 接口定义的方法都是抽象,他们被自动地设置为public。
  5. 接口也被保存为.java文件,文件名和类名相同。
public interface Animal {
    void breath();
}

public class Tiger implements Animal {
    public void breath() {
        System.out.println("老虎用肺呼吸");
    }
}

public class Test {
    public static void main(String[] args) {
        Tiger tiger = new Tiger();
        tiger.breath();
    }
}

接口之间也可以有继承关系。继承接口的接口拥有它的父接口的方法,它还可以定义自己的方法,实现这个子接口的类,要实现所有这些方法。

public interface Animal {
    void breath();
}

public interface Mammal extends Animal {
    void run();
}

public class Tiger implements Mammal {
  // 类要实现接口的所有方法
    public void breath() {
        System.out.println("老虎用肺呼吸");
    }
    
    public void run() {
        System.out.println("老虎用四条腿跑");
    }
}

public class Test {
    public static void main(String[] args) {
        Tiger tiger = new Tiger();
        
        tiger.breath();
        tiger.run();
    }
}

跟抽象类一样,接口也不可以实例化,但是可以声明接口类型的变量,它的值必须是实现了该接口的类的对象。

// 只能调用在 Animal 接口中定义的方法
Animal tiger= new Tiger();
// 通过强制转换,就可以调用
((Tiger) tiger).run();
((Mammal)tiger).run();

// 在 Animal 和 Mammal 中定义的方法都可以调用
Mammal tiger = new Tiger();

接口的另一个重要应用是用它来创建常量组。

类可以直接使用接口中定义的常量。把一些固定的常量组值放在接口中定义,然后在类中实现该接口,

public interface Day {
    int MORNING = 1;
    int ARTERNOON = 2;
    int NIGHT = 3;
}

public class Test implements Day {
    public static void main(String[] args) {
        System.out.println(MORNING + "," + ARTERNOON + "," + NIGHT);
    }
}

抽象类和接口的比较:

  1. 一个类可以实现多个接口,但是只能继承一个抽象类。
  2. 抽象类可以有抽象的方法,也可以有已经实现的方法,继承它的子类可以对方法进行重写,而接口中定义的方法必须全部为抽象方法。
  3. 在抽象类中定义的方法,它们的修饰符可以是publib、protected、private,也可以是默认值,但是在接口中定义的方法全是public。
  4. 抽象类可以有构造函数,接口不能。两者都不能实例化,但是都能通过他们来存放子类对象或实现类的对象,也可以说它们都可以实现多态。
原文地址:https://www.cnblogs.com/lialong1st/p/10286906.html