1.接口是常量值和抽象方法定义的集合
2.从本质上讲,接口是一种特殊的抽象类,这种抽象类只包含常量和方法的定义,没有变量和方法的实现
3.多个无关的类可以实现同一接口
4.一个类可以实现多个无关的接口
5.与继承类似,接口与实现类之间存在着多态性
接口的特性:
接口可以多重实现。
接口中声明的属性默认为public final staic ,也只能是public final static
接口中只能定义抽象方法,而且这些方法默认为public的,也只能是public
接口也可能继承其它的接口,并且可能添加新的属性和抽象方法
public class TestInterface {
public static void main(String[] args) {
// 多个无关的类实现同一接口
System.out.println("---多个无关的类实现同一接口----");
Singer s1 = new Student("张同学");
s1.sing();
s1.sleep();
Singer s2 = new Teacher("朱老师");
s2.sing();
s2.sleep();
// 一个类实现不同的接口
System.out.println("---一个类实现不同的接口----");
Teacher t1 = new Teacher("张老师");
t1.sing();
t1.sleep();
t1.paint();
t1.eat();
t1.teach();
//多态的实现
System.out.println("---多态的实现----");
Student student=new Student("李同学");
Teacher teacher=new Teacher("吴老师");
f(student);
f(teacher);
}
static void f(Singer s){
s.sing();
s.sleep();
}
}
// 接口
interface Singer {
void sing();
void sleep();
}
interface Painter {
void paint();
void eat();
}
// 实现Singer接口的Student类
class Student implements Singer {
String name;
public Student(String name) {
this.name = name;
}
public void sing() {
System.out.println(name + " is singing...");
}
public void sleep() {
System.out.println(name + " is sleeping...");
}
void study() {
System.out.println(name + " is studying...");
}
}
//实现Singer、Painter接口的Teacher类
class Teacher implements Singer, Painter {
String name;
Teacher(String name) {
this.name = name;
}
public void sing() {
System.out.println(name + " is singing...");
}
public void sleep() {
System.out.println(name + " is sleeping...");
}
public void paint() {
System.out.println(name + " is painting...");
}
public void eat() {
System.out.println(name + " is eating...");
}
public void teach() {
System.out.println(name + " is teaching...");
}
}