Java-接口(interface)
一、格式
public interface 接口名{
}
二、实现方式
public class 类名 implements 接口名1,接口名2{
}
三、接口的成员特点
-
成员变量:必须是常量,默认修饰符为public static final
public interface TestInterface { public final static int n=10;//标准形式 } public interface TestInterface { int n=10;//这样写不会报错,编译时应该会加上前面的默认修饰符。 } public interface TestInterface { private int N=10;//错误的,接口中的变量必须是public修饰,其他三种都不行。 }//编译报错:
-
构造方法:接口中不能存在构造方法
public interface TestInterface { public TestInterface(){ }//错误 }
-
成员方法:必须是抽象方法,默认修饰符为public abstract
public interface TestInterface { public void method(){}//错误,接口中的成员方法必须是抽象方法,不能含有方法体 } public interface TestInterface { public abstract void method();//标准形式 }
四、接口特点
-
接口不能单独实例化。
-
一个类实现一个接口时,要么为抽象类,要么重写接口中所有的方法。
//1.重写接口中的所有方法 public interface TestInterface { public abstract void method(); } public class TestClass implements TestInterface{ @Override public void method() { } } //2.用abstract修饰为抽象类 public interface TestInterface { public abstract void method(); } public abstract class TestClass implements TestInterface{ }
五、抽象类和接口的区别
1.语法区别
抽象类:
属性:变量;常量
方法:构造方法;抽象方法;非抽象方法
接口:
属性:常量
方法:抽象方法
2.设计理念区别
抽象类:对类进行抽象,包括属性、行为
接口:对行为进行抽象,主要包括行为。
记录学习过程,仅供参考,有错或者叙述不当请指出。