提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
1.接口的语法格式:
[ public ] interface 接口名称 [extends 父类接口名列表]{
[public] [static] [final] 数据类型 成员变量=常量
...
[public] [abstract] 返回值类型 方法名 (参数表);
...
}
2.接口注意事项:
(1)用 implements子句表示一个类实现了某个接口,接口使用extends可以继承多个接口
(2)一个接口可以继承多个接口,接口要实现具体的功能必须有实现它的子类,实现接口的子类必须重写接口中所有抽象方法
(3)一个类只能继承一个类,但可以继承多个接口
(4)接口需要通过多态方式才能创建对象
(5)接口中子类可以是子类,但没有多大意义
3.实现接口的思想:可以返回接口,接口虽然不能被实例化,但是接口的实现类都可以向上转型为接口
4.接口作为形式参数和返回值时的用法
接口作为方法的参数进行传递
(1)必须传递进去一个接口的实现类对象
(2)接口名作为形式参数:如果看到一个方法的形式参数是一个接口类型,那么就传递一个该接口的实现类对象
方法一:常规方法
//玩接口
interface Playing{
void playing();
}
//学生类
class Student implements Playing {
@Override
public void playing() {
// TODO Auto-generated method stub
System.out.println("I can playing");
}
}
public class Text {
public static void main(String[] args) {
//测试类
Student s = new Student();
naughty(s); //打印结果:I can playing
}
//顽皮类
public static void naughty(Playing s) { //接口作为参数。
s.playing();
}
}
匿名内部类语法:
new 类名或接口名(){
重写方法
}
方法二:匿名内部类方法
//玩接口
interface Playing{
void playing();
}
public class Text {
public static void main(String[] args) {
//测试类
naughty(new Playing() {
@Override
public void playing() {
// TODO Auto-generated method stub
System.out.println("I can playing");
//打印结果:I can playing
}
});
}
//顽皮类
public static void naughty(Playing play) { //接口作为参数。
play.playing();
}
}
Lambda语法:
()->{};
[Lambda是函数式接口为特有接口]
使用 "->"将参数和实现逻辑分离;
( ) 中的部分是需要传入Lambda体中的参数;
{ } 中部分,接收来自 ( ) 中的参数,完成一定的功能。
方法三:Lambda表达式,函数式接口特有
//玩接口
@FunctionalInterface
interface Playing{
void playing();
}
public class Text {
public static void main(String[] args) {
//测试类
naughty(()->System.out.println("I can playing"));
//打印结果:I can playing
}
//顽皮类
public static void naughty(Playing play) { //接口作为参数。
play.playing();
}
}
接口作为方法的返回值进行传递:
(1)必须返回一个接口的实现类的对象。
(2)接口名作为返回值类型:如果看到一个方法的返回值类型是一个接口类型,那就返回一个该接口的实现类对象
方法一:常规方法
//玩接口
@FunctionalInterface
interface Playing{
void playing();
}
//学生类
class Student implements Playing {
public void playing() {
System.out.println("I can playing");
}
}
public class Text {
public static void main(String[] args) {
Student s=new Student();
s.playing(); //打印结果:I can playing
}
public static Playing naughty() {
return new Student();//返回接口实现类的对象。
}
}
//方法二:Lambda表达式,函数式接口特有
//玩接口
@FunctionalInterface
interface Playing{
void playing();
}
public class Text {
public static void main(String[] args) {
Playing play=naughty();
play.playing();
//打印结果:I can playing
}
public static Playing naughty() {
return ()->System.out.println("I can playing");
}
}
方法三:匿名内部类的方法
//玩接口
@FunctionalInterface
interface Playing{
void playing();
}
public class Text {
public static void main(String[] args) {
Playing play=naughty();
play.playing();
//打印结果:I can playing
}
public static Playing naughty() {
return new Playing() {
@Override
public void playing() {
System.out.println("I can playing");
}};
}
}
java1.8的出现,使用lambda表达式会使代码更加简洁,增加代码的可读性