天天看点

java定义一个接口shape_Shape接口定义如下:interface Shape{double pi=3.14;double area();}用java编写类Circle、Square、和Rec...

java定义一个接口shape_Shape接口定义如下:interface Shape{double pi=3.14;double area();}用java编写类Circle、Square、和Rec...

优质解答

public interface Shape

{

double pi=3.14;

double area();

}

public class Circle implements Shape

{

private double radius;

public Circle(double radius)

{

\x05 this.radius=radius;

}

public double area()

{

\x05 double area;

\x05 area=pi*radius*radius;

\x05 System.out.println("area="+area);

\x05 return area;

}

public static void main(String[] args)

{

\x05 Shape ox=new Circle(2.0);

\x05 ox.area();

}

}

public class Square implements Shape

{

private double length;

public Square(double length)

{

\x05 this.length=length;

}

public double area()

{

\x05 double area;

\x05 area=length*length;

\x05 System.out.println("area="+area);

\x05 return area;

}

public static void main(String[] args)

{

\x05 Shape ox=new Square(2.0);

\x05 ox.area();

}

}

public class Rectangle implements Shape

{

private double length;

private double width;

public Rectangle(double length,double width)

{

\x05 this.length=length;

\x05 this.width=width;

}

public double area()

{

\x05 double area;

\x05 area=length*width;

\x05 System.out.println("area="+area);

\x05 return area;

}

public static void main(String[] args)

{

\x05 Shape ox=new Rectangle(2.0,4.0);

\x05 ox.area();

}

}我把它写在三个不同的代码里,你要是愿意改那就把它写在一起也可以,用内部类吧.