1.接口的作用:方法声明和方法实现相分离,每实现接口的类根据自身的实际情况,给出实际实现方法;
//平面图形接口
public interface PlaneGraphics2
{
public abstract double area(); //计算面积
public abstract double perimeter(); //计算周长
public abstract void print(); //显示
}
//长方形类
public class Rectangle2 implements PlaneGraphics2
{
protected double length;
protected double width;
public Rectangle2(double length,double width){
this.length=length;
this.width=width;
}
public Rectangle2(double width){ //正方形
this.length=width;
this.width=width;
}
public Rectangle2(){
this(0,0); //根据参数调用本类的构造方法
}
public Rectangle2(Rectangle2 r1){
this(r1.length,r1.width);
}
public double area(){ //计算面积
return this.width*this.length;
}
public double perimeter(){
return (this.width+this.length)*2; //计算周长
}
public void print(){
if(this.length==this.width)
System.out.print("一个正方形,边长为:"+this.length);
else
System.out.print("一个长方形,长度为"+this.length+"宽度为:"+this.width);
System.out.println(",面积为:"+this.area()+",周长为"+this.perimeter());
}
public static void main(String args[]){
Rectangle2 r1=new Rectangle2(10,20);
r1.print();
r1=new Rectangle2(10);
r1.print();
}
}
一个类可以 继承一个父类 并 实现多个接口:
//立体图形接口
public interface SolidGraphics1
{
public abstract double volume(); //计算体积
}
//长方体类
public class Cuboid1 extends Rectangle2 implements SolidGraphics1
{
protected double height;
public Cuboid1(double length,double width,double height){
super(length,width); //调用父类的构造方法
this.height=height;
}
public Cuboid1(Rectangle2 r1,double height){
this(r1.length,r1.width,height); //调用本类构造函数
}
public Cuboid1(double width){
this(width,width,width);
}
public Cuboid1(){
this(0,0,0);
}
public double area(){
return super.perimeter()*this.height+2*super.area(); //super引用父类的同名成员
}
public double volume(){
return super.area()*this.height;//super引用父类的同名成员
}
public void print(){
System.out.print("一个长方体,长度为:"+this.length+",宽度为:"+this.width+
",高度为:"+this.height);
System.out.print(",表面积为:"+this.area()+",体积为:"+this.volume());
}
public static void main(String args[]){
Cuboid1 c1=new Cuboid1(10,20,30);
c1.print();
}
}
球类实现多个接口:
//实现多个接口,实现平面图形接口和立体图形接口
public class Globe1 implements PlaneGraphics2,SolidGraphics1
{
private double radius;
public Globe1(double radius){
this.radius=radius;
}
public Globe1(){
this(0);
}
public double area(){ //计算表面积,覆盖PlaneGraphics2接口中的抽象方法
return 4*Math.PI*this.radius*this.radius;
}
public double perimeter(){ //虽然球没有周长的概念,也必须覆盖接口中的抽象方法
return 0;
}
public double volume(){
return Math.PI*this.radius*this.radius*this.radius*4/3;
}
public void print(){
System.out.println("一个球,半径为:"+this.radius+",表面积为:"+this.area()+
",体积为:"+this.volume());
}
public static void main(String args[]){
Globe1 g1=new Globe1(10);
g1.print();
}
}