Java ——接口
本节重点思维导图
定义:
public interface Traffic { public static final int sits = 4; public abstract void run(); public abstract void stop(); }
调用:
public class bwm implements Traffic{ @Override public void run() { System.out.println("bwm:500km/h"); } @Override public void stop() { System.out.println("bwm:10m"); } }
测试:
public class demo1 { public static void main(String[] args) { Traffic traffic; traffic = new cat(); System.out.println(traffic.sits); traffic.run(); traffic.stop(); } }
示例:
public interface Traffic { public static final int SEATS = 8; public abstract void run(); public abstract void brake(); static void fun1() { System.out.println("static"); } default void fun2() { System.out.println("default"); } } public static void main(String[] args) { Traffic.fun1(); Traffic traffic= new BMW(); traffic.fun2(); // traffic.fun1(); BMW bmw= new BMW(); bmw.fun2(); }
接口的继承
Java是单继承多实现
单继承:
一个类只能有一个父类
public class D extends D1 ,D2{
}
多实现:
Ø 一个类可以同时实现多个接口
Ø 当一个类同时实现多个接口时,它需要同时实现这些接口中声明的所有抽象方法
public interface A { void fun1(); } |
public interface B { void fun2(); } |
public class AAA implements A,B{ @Override public void fun1() {
} @Override public void fun2() {
} } |
接口之间可以相互继承
public interface A { void fun1(); } |
public interface B extends A{ // 接口B继承自接口A void fun2(); } |
public class AB implements B{ @Override public void fun1() { } @Override public void fun2() { } } |