java基礎:interface

十五樓亮哥發表於2015-02-01

一:例子

public interface Singer {
	public static final int  i = 0;
	public void sing();
	public void sleep();

}

public class Student implements Singer {
	private String name;
	Student(String name){
		this.name = name;
		
	}
	@Override
	public void sing() {
		System.out.println("student is singing");
	}

	@Override
	public void sleep() {
		System.out.println("student is sleeping");
	}

	public void study() {
		System.out.println("student is studying");
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}


public class Test {
	public static void main(String[] args) {
		Singer s1 = new Student("le");
		s1.sleep();
		s1.sing();
		//s1.study(); error
	}
}

二:總結

1:介面是抽象方法和常量值定義的集合
2:從本質上講,介面是一種特殊的抽象類,只包含常量和方法的定義,沒有方法的實現
3:介面可以實現多重實現
4:介面中宣告的屬性預設為public static final,也只能是public static final
5:介面中只能定義抽象方法,預設為public,也只能是public
6:介面可以繼承其他介面,並新增新的屬性和抽象方法