友情提示:如果没有了解类的继承请先去看一下我前面的 Java 继承
目录
1.接口的介绍
1.1接口定义的基本格式
public interface 接口名{ content }
1.2 接口的组成
- 抽象方法
- 默认方法
- 静态方法
- 私有方法
- 常量 public static final 数据类型 变量名 (在接口中定义变量时必须赋值)
2.接口中的方法
2.1 抽象方法
2.1.1 基本格式
public abstract 返回值类型 方法名(){ 没有方法体 }
(可省略 pulic 和 abstract )
在接口中,没有 public abstract 关键字的方法依旧是抽象方法
2.1.2 代码举例
public interface method1 {
public abstract void show();
}
public class method2 implements method1{
public void show() {
System.out.print("抽象方法show()");
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
method2 one=new method2(); //"抽象方法show()"
one.show();
}
}
2.2 默认方法
2.2.1 基本格式
public default 返回值类型 方法名(){ 方法体 }
( 可以省略public )( 不可省略default )
2.2.2 代码举例
public interface method1 {
public abstract void show();
public default void add() {
System.out.print("接口的默认方法add()");
}
}
public class method2 implements method1{
public void show() {
System.out.print("抽象方法show()");
}
public static void main(String[] args) {
method2 one=new method2();
one.add();
}
}
2.2.3 总结一下
默认方法可以用在接口升级的时候
所谓接口升级就是在 已有接口中我们需要新增一些抽象方法时,我们必须在接口的实现类进行重写新增的抽象方法。
如果我们不想重写方法的时候,我们就可以在接口中使用默认方法来实现具体的代码
2.3 静态方法
2.3.1 基本格式
public static 返回值类型 方法名(){ 方法体 }
静态方法的使用:接口名.静态方法名()
2.3.2 代码举例
public interface method1 {
public abstract void show();
public default void add() {
System.out.print("接口的默认方法add()");
}
public static void get() {
System.out.print("接口的静态方法get()");
}
}
public class method2 implements method1{
public void show() {
System.out.print("抽象方法show()");
}
public static void main(String[] args) {
method2 one=new method2();
one.get(); // 报错
method1.get(); // "接口的静态方法get()"
}
}
2.3.3 总结一下
如果用接口实现类的对象进行访问会出现错误
method2 one=new method2();
one.get(); // 报错
2.4 私有方法
2.4.1 基本格式
private 返回值类型 方法名(){ 方法体 }
私有方法只能在接口的默认方法和静态方法中 接口的实现类是不能访问的
2.4.2 代码举例
私有方法在默认方法中
public interface method1 {
public default void add() {
hello();
}
private void hello() {
System.out.print("hello everyone");
}
}
public class method2 implements method1{
public static void main(String[] args) {
method2 one=new method2();
one.add();
}
}
私有方法在静态方法中
public interface method1 {
public static void add() {
hello();
}
private static void hello() {
System.out.print("hello everyone");
}
}
public class method2 implements method1{
public static void main(String[] args) {
method2 one=new method2();
one.add();
}
}
2.4.3 总结一下
私有方法只存在于接口内部,接口的实现类是访问不了