JAVA SE(十一)—— JAVA 面向對象5(接口 interface)

一、Java 接口 interface

1、接口概述

(1)接口是一種特殊的類,接口可以多實現,接口中的屬性默認是公開的、靜態的,最終的常量。

public static final int NUM = 3

(2)接口中只有抽象方法,但是可以省略abstract關鍵字。

(3)interface:class用於定義類,但是在接口中,用interface定義接口。

public interface Person{
		
}

(4)implements:用於子類中,實現接口中的方法。

public class student implements Person{

}

(5)接口中常見定義:常量,抽象方法。

  • 常量:public static final
public static final int NUM = 3
  • 方法:public abstract
public abstract void study();

2、接口的作用

規範子類的行爲

3、接口示例

定義一個Person類,具有屬性sleep()方法和eat()方法

public interface Person{
	public void sleep();
	public void eat();
}

定義一個China類,具有屬性country()

public interface China{
	public void country();
}

定義一個Student類實現Person和China接口

public class Student implements Person,China{
	public void sleep() {
		System.out.println("學生睡覺");
	}
	public void eat() {
		System.out.println("學生吃飯");
	}
	public void country() {
		System.out.println("學生是中國人");
	}
}

定義一個Worker類實現Person和China接口

public class Worker implements Person,China{
	public void sleep() {
		System.out.println("工人睡覺");
	}
	public void eat() {
		System.out.println("工人吃飯");
	}
	public void country() {
		System.out.println("工人是中國人");
	}
}

測試類

public class Demo{
	public static void main(String[] args) {
		//創建Student類對象並調用其方法
		Student student = new Student();
		student.sleep();
		student.eat();
		student.country();
		//創建Worker類對象並調用其方法
		Worker worker = new Worker();
		worker.sleep();
		worker.eat();
		worker.country();
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章