首页 > 代码库 > 接口(interface)与多态

接口(interface)与多态

1. 接口(interface)是抽象方法与常量值的集合;

2. 从本质上来讲,接口是一种特殊的抽象类,这种抽象类中只包含常量与方法的定义,而没有变量和方法的实现;

3. 接口中声明的属性默认为:public static final,也只能是:public static final,(接口中成员变量的定义);

4. 接口中只能定义抽象方法,而且这些方法默认为public,也只能是public的;

5. 接口可以继承其他的接口,并添加新的属性和抽象方法;

6. 多个无关的类可以实现同一个接口,一个类可以实现多个无关的接口;

7. 与继承关系类似,接口与实现类之间存在多态性:

    多态的三个条件:继承,重写,父类引用指向子类对象;

    由于Java中没有多继承,一个类只能有一个父类。一个父类可以有多个子类,而在子类里可以重写父类的方法;

    用接口可以实现多继承,一个类或是可以同时实现多个接口;

    一般而言,接口有利于代码的扩展,而继承则有利于代码功能的修改

8. Demo

Demo_1

public interface Runner{
	int id = 1; // 相当于:public static final int id = 1;
	public void start();
	public void run();
	public void stop();
}
// 正确

 Demo_2

interface Singer{
	public void sing();
	public void sleep();
}

class Sudents implements Singer{
	private String name;
	
	public Sudents(String name) {
		this.name = name;
	}
	public void study(){
		System.out.println("Studying");
	}
	public String getName(){
		return name;
	}
	public void sing() { // @Override
		System.out.println("Student is Singing");
	}
	public void sleep() { // @Override
		System.out.println("Student is sleping");
	}
}
// 正确

 Demo_3

interface Singer{
	public void sing();
	public void sleep();
}
interface Painter{
	public void paint();
	public void eat();
}
class Student implements Singer{
	private String name;
	public Student(String name) {
		this.name = name;
	}
	public void study(){
		System.out.println("studying");
	}
	public String getName(){
		return name;
	}
	public void sing() { // @Override
		System.out.println("student is singing");
	}
	public void sleep() { // @Override
		System.out.println("student is sleeping");	
	}
}
class Teacher implements Singer, Painter{
	private String name;
	public Teacher(String name) {
		this.name = name;
	}
	public String getName(){
		return name;
	}
	public void teach(){
		System.out.println("teaching");
	}
	public void paint() { // @Override
		System.out.println("teacher is painting");
	}
	public void eat() { // @Override
		System.out.println("teacher is eating");
	}
	public void sing() { // @Override		
		System.out.println("teacher is singing");
	}
	public void sleep() { // @Override
		System.out.println("teacher is sleeping");
	}
}
public class Test {
	public static void main(String[] args){
		Singer s1 = new Student("s1");
		s1.sing();
		s1.sleep();
		Singer t1 = new Teacher("t1"); //相当于继承中的父类引用指向子类对象
		t1.sing();
		t1.sleep();
		Painter p1 = (Painter) t1; //相当于继承中的父类引用指向子类对象
		p1.paint();
		p1.eat();
	}
}
// 正确

 Demo_3的运行结果:

     student is singing
     student is sleeping
     teacher is singing
     teacher is sleeping
     teacher is painting
     teacher is eating

接口(interface)与多态