一,接口的定义用interface,而不是用class,接口中定义了一个没有任何方法体实现的方法-这是接口中定义方法的原则,只要定义方法返回类型,方法名,参数表,不能有实现!值得注意的是,方法前无论是否写了public限定符,接口中的方法都是public型的。
二,不能直接用接口创建对象,而是要再编写一个类去实现这个接口。
具体的例子如下:
//创建一个关于人的接口
//再创建一个关于eat的接口
//创建一个Child类实现person和eat的接口,一个类可以同时实现几个接口
三,一个class可以在extends一个class的基础上再去implements多个interface
如
public class nustudent extends student implements person{
}
四,如果两个接口中出现了名字和参数都一样的方法,子类来实现的时候不会有影响,因为这两个接口中都没有方法体。
二,不能直接用接口创建对象,而是要再编写一个类去实现这个接口。
具体的例子如下:
//创建一个关于人的接口
public interface person {
//接口的属性必须要初始化
public final static String name="小草";
public void study();
public void play();
}
//再创建一个关于eat的接口
public interface eat {
public void eatcandy();
}
//创建一个Child类实现person和eat的接口,一个类可以同时实现几个接口
public class Child implements person,eat {
public void study(){
System.out.println(name+"在游戏中学习");
}
public void play(){
System.out.println(name+"正在玩泥巴");
}
public void eatcandy(){
System.out.println(name+"喜欢吃糖");
}
}
//创建一个测试类
public class Test {
public static void main(String[] arfs){
Child ch=new Child();
ch.eatcandy();
ch.study();
ch.play();
}
}
输出的结果为
小草喜欢吃糖
小草在游戏中学习
小草正在玩泥巴
三,一个class可以在extends一个class的基础上再去implements多个interface
如
public class nustudent extends student implements person{
}
四,如果两个接口中出现了名字和参数都一样的方法,子类来实现的时候不会有影响,因为这两个接口中都没有方法体。