java 接口interface
13:13
package oop;
/*
* 1. 接口是比抽象类还抽象的抽象类;可以更加规范的对子类进行约束
* 2.抽象类还提供某些具体实现,接口不提供任何实现
* 3.接口是两个模块之间通信的标准
* 4.接口和实现类不是父子的关系,是实现规则的关系
*
* */
//接口只定义常量(static final)
public interface MyInterface {
int MAX_AGE = 100;//默认是常量,和下面的语句等价
public static final int MAX_AGE1 = 100;
void test01();//默认是抽象方法,和下面的语句等价
public abstract void test02();
}
// 子类 通过 implements 来实现接口中的规范
class MyClass implements MyInterface {
public void test01() {
System.out.println(MAX_AGE);
}
public void test02() {
System.out.println(MAX_AGE1);
}
}
实例
package oop;
public class TestInterface {
public static void main(String[] args) {
Volant v = new Angel();//想让v 实现谁的方法就定义成谁此处为 Volant,
v.fly();
// v.helpOther(); //就不能实现 Honest 的方法了
Honest h = new GoodMan();
h.helpOther();
}
}
//飞行接口
interface Volant {
int FLY_HEIGHT = 1000;
void fly();
}
//善良接口
interface Honest {
void helpOther();
}
class Angel implements Volant,Honest {
public void helpOther() {
System.out.println("Anger help other...");
}
public void fly() {
System.out.println("fly");
}
}
class GoodMan implements Honest {
public void helpOther() {
System.out.println("I am kind");
}
}
class Birdman implements Volant {
public void fly() {
System.out.println("I am a birdman");
}
}
接口的多继承
package oop;
public class TestInterface2 {
}
interface A {
void testa();
}
interface B {
void testb();
}
// 接口可以多继承,类只有单继承
interface C extends A,B {
void testc();
}
class Test implements C {
public void testa() {
}
public void testb() {
}
public void testc() {
}
}