接口的继承
接口也有继承性,在定义接口时可以用关键字 extends 表明本接口是某一个接口的子接口。
- 一个子接口可以继承多个父接口。
- 子接口将继承父接口中的常量、抽象方法、默认方法,不能继承静态方法。
- 接口的实现类不能继承接口的静态方法。
示例:
package ch08;
interface Face1{
final double PI=3.14;
abstract double area();
}
interface Face2{
abstract void setColor(String c);
}
interface Face3 extends Face1,Face2{
abstract void volume();
}
public class Cylinder implements Face3{
private double radius;
private int height;
protected String color;
public Cylinder(double r,int h){
radius=r;
height=h;
}
public double area(){
return PI*radius*radius;
}
public void setColor(String c){
color=c;
System.out.println("颜色:"+color);
}
public void volume(){
System.out.println("圆柱体体积="+area()*height);
}
public static void main(String[] args){
Cylinder volu=new Cylinder(3.0,2);
volu.setColor("红色");
volu.volume();
}
}
利用接口实现类的多重继承
Java只支持类的单一继承,但允许类在实现接口时呈现多重继承的特性。
示例:
package ch08;
interface Face1{
final double PI=3.14;
abstract double area();
}
interface Face2{
abstract void setColor(String c);
}
interface Face3{
abstract void volume();
}
public class Cylinder implements Face1,Face3{ //Cylinder 类实现并继承两个接口
private double radius;
private int height;
protected String color;
public Cylinder(double r,int h){
radius=r;
height=h;
}
public double area(){
return PI*radius*radius;
}
public void setColor(String c){
color=c;
System.out.println("颜色:"+color);
}
public void volume(){
System.out.println("圆柱体体积="+area()*height);
}
public static void main(String[] args){
Cylinder volu=new Cylinder(3.0,2);
volu.setColor("红色");
volu.volume();
}
}
本文详细介绍了Java中接口的继承特性,包括如何使用关键字extends声明子接口,子接口如何继承父接口的常量、抽象方法及默认方法。同时,通过具体示例说明了Java类在实现接口时展现的多重继承特性。
2212

被折叠的 条评论
为什么被折叠?



