2018暑期周总结报告(四)

JAVA只支持单重继承,不支持多重继承,即一个类只能有一个父类。但是在实际应用中,又经常需要使用多重继承来解决问题。为了解决该问题,JAVA提供了接口来实现类的多重继承功能。

JAVA语言使用关键字interface来定义一个接口。

语法格式如下:

【修饰符】interface 接口名【extends 父接口名列表】{

public】[static] [final]常量;

public】【abstract】方法;

}

接口与抽象类的共同点:

(1)      接口与抽象类都不能被实例化,能被其他类实现和继承;

(2)      接口和抽象类都可以包含抽象方法,实现接口或继承抽象类的普通子类都必须实现这些抽象方法。

实例

public interface Animals{

void Eat(String s);

}

public class Dog implements Animals{

Public void Eat(String s){

     System.out.println(“我是小狗嘎逗,我爱吃“+s);

}

}

public class Cat implements Animals{

Public void Eat(String s){

     System.out.println(“我是小猫咪咪,我爱吃“+s);

}

}

public class Example{

public static void main(String[] args){

animals ani;

ani=new Dog();

ani.Eat(“骨头“);

ani=new Cat();

ani.Eat(“鱼“);

}

}

运行结果

我是小狗嘎逗,我爱吃骨头

我是小猫咪咪,我爱吃鱼

 

猜你喜欢

转载自www.cnblogs.com/mawangwang/p/9419088.html