Java接口interface

时间:2021-07-14 18:35:01

Java接口interface

1、多个无关的类可以实现同一个接口。

2、一个类可以实现多个无关的接口。

3、与继承关系类似,接口与实现类之间存在多态性。

接口(interface)是抽象方法和常量值的定义的集合,从本质上讲,接口是一种特殊的抽象类,这种抽象类中只包含常量和方法的定义,而没有变量和方法的实现。实现一个接口,用implements ,实现一个接口必须重写接口中的所有方法。

接口定义的举例:

public interface Runner{
public static final int id=1;
public void start();
public void run();
public void stop();
}

接口的特性:

1、接口可以多重实现,即一个类可以实现多人接口。

2、接口中声明的属性默认为public static final ;也只能是public static final 。

3、接口中只能定义抽象方法,而且这些方法默认为public ,也只能是public 。

4、接口可以继承其它的接口,并添加新的属性和抽象方法。

接口的举例:

interface Singer{
public void sing();
public void sleep();
}
Class Student implements Singer{
private String name;
Student(String name){
this.name=name;
}
public vod study(){
System.out.println("studying");
}
public Sting getName(){
return name;
}
public void sing(){
System.out.println("Student is singing");
}
public void sleep(){
System.out.println("student is sleeping");
}
}

接口与实现类之间的多态性举例:


public class Test{
public static void main(String arg[]){
//Singer是接口,在上面已经定义了。
//student是接口Singer有实现类。
Singer s1=new student("le");
s1.sing();
//s1此时调用的是student中的sing()方法。
s1.sleep();
}
}

接口的综合举例:


public interface Valuable{
public double getMoney();
}
interface Protectable{
public void beProtected();
}
//接口与接口之间可以继承
interface A extends Protectable{
void m();
}
abstract class Animal{
private String name;
abstract void enjoy();
}
//继承一个类要重与父类中所有的方法,或者是实现一个接口要重写接口中的所有方法。
class GoldenMonkey extends Animal implements Valuable,Protectable{
public double getMoney(){
return 10000;
}
public void beProtectable(){
System.out.println("live in the room");
}
public void enjoy(){
}
public void test(){
Valuable v=new GoldenMonkey();
v.getMonen();
Protectable p=(Protectable)v;
p.beProtectable();
}
}
class Hen implements A{
public void m(){}
public void beProtected(){}
}