女排世界杯_1966世界杯 - ezrjnk120.com

Java中接口的实现与方法的调用

2025-05-29 01:32:23

package four;

//定义一个接口

interface Animals4{

int ID=1;//定义全局变量

//定义抽象方法

void breathe();

//定义一个默认方法

default void getType(String type) {

System.out.println("该动物属于:"+type);

}

//定义一个静态方法

static int getID() {

return Animals4.ID;

}

}

//实现接口

class Cat2 implements Animals4{

//实现breathe()方法

public void breathe() {

System.out.println("猫在呼吸。");

}

}

//定义测试类

public class Test04_Interface {

@SuppressWarnings("static-access")

public static void main(String[] args) {

System.out.println(Animals4.ID);//接口名调用类方法

Cat2 cat=new Cat2();//实例化Cat类

System.out.println(cat.ID);//获取接口中的全局变量

cat.breathe();//调用cat对象中的breathe()方法

cat.getType("猫科");//通过接口实现类Cat的实例化对象,接口默认方法

}

}

注意:

1.JDK 8开始,接口中可以包含三类方法:抽象方法、默认方法和静态方法,默认方法和静态方法可以有方法体,且静态方法可以通过“接口名.方法名”的形式来调用,而抽象方法和默认方法只能通过接口实现类的实例对象来调用;

2.一个类可以通过extends关键字继承另一个类的同时通过implements关键字实现一个或多个接口(逗号隔开);

3.接口的实现类,如果是抽象类,只需实现接口中的部分抽象方法即可,否则必须实现接口中的所有抽象方法;

4.接口与接口之间可以通过extends关键字实现继承。