JAVA面向对象(五)—— Java接口 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、接口Demo

//定义一个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();
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43592512/article/details/89702576