2个回答
展开全部
等了一下午?给你写了一个,用的是接口。。。
import java.text.DecimalFormat;
interface Shape{
public double getArea();
}
class Circle implements Shape{
private double radius;
public Circle(double r){
radius = r;
}
public double getArea(){
return Math.PI * radius *radius;
}
}
class Triangle implements Shape{
private double lineLong;
public Triangle(double l){
lineLong = l;
}
public double getArea(){
return lineLong * lineLong *Math.sin(Math.PI/3) /2;
}
}
class Square implements Shape{
private double lineLong;
public Square(double l){
lineLong = l;
}
public double getArea(){
return lineLong * lineLong;
}
}
public class Area{
public static void main(String[] args){
DecimalFormat fmt = new DecimalFormat("0.00");
Shape s1 = new Circle(2.0);
System.out.println("Circle area is:" + fmt.format(s1.getArea()));
Shape s2 = new Triangle(2.0);
System.out.println("Triangle area is: " + fmt.format(s2.getArea()));
Shape s3 = new Square(2.0);
System.out.println("Square area is: " + fmt.format(s3.getArea()));
}
}
要是非让用extends,就把interface 改成 class
把implements改成 extends,别的都不用改
import java.text.DecimalFormat;
interface Shape{
public double getArea();
}
class Circle implements Shape{
private double radius;
public Circle(double r){
radius = r;
}
public double getArea(){
return Math.PI * radius *radius;
}
}
class Triangle implements Shape{
private double lineLong;
public Triangle(double l){
lineLong = l;
}
public double getArea(){
return lineLong * lineLong *Math.sin(Math.PI/3) /2;
}
}
class Square implements Shape{
private double lineLong;
public Square(double l){
lineLong = l;
}
public double getArea(){
return lineLong * lineLong;
}
}
public class Area{
public static void main(String[] args){
DecimalFormat fmt = new DecimalFormat("0.00");
Shape s1 = new Circle(2.0);
System.out.println("Circle area is:" + fmt.format(s1.getArea()));
Shape s2 = new Triangle(2.0);
System.out.println("Triangle area is: " + fmt.format(s2.getArea()));
Shape s3 = new Square(2.0);
System.out.println("Square area is: " + fmt.format(s3.getArea()));
}
}
要是非让用extends,就把interface 改成 class
把implements改成 extends,别的都不用改
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询