使用不同的引用类型和实例类型创建对象

时间:2015-01-16 06:08:20

标签: java interface

如何改进计划实施?使用引用类型作为接口和实例类型作为实现类进行测试时,程序失败。专注于使用不同的引用类型和实例类型创建对象。

package com;
interface Shape {
public abstract double getArea(double d);
}
public class TestCircle {
public static void main(String[] args) {

    Circle s = new Circle();
    System.out.println(s.getArea(5));
    System.out.println(calculateArea(s,5));
    Shape s1 = new Square();
    System.out.println(calculateArea(s1,5));
}
public static double calculateArea(Shape s, double d){
    if(s==null) return 0.0;
    return s.getArea(d);
}
}
class Circle implements Shape{
public double getArea(double d){
    if(d<0) return 0.0;
    return d*d*(22.0/7);
}
}
class Square implements Shape{
public double getArea(double d){
    //if(d<0)   return 0.0;
    return d*d;
}
}

1 个答案:

答案 0 :(得分:-1)

稍微重新考虑你的代码。详细说明你想要实现的目标。您可能不需要静态calculateArea()!

package com;
interface Shape {
    public double getArea(double d);
}
public class TestCircle {
    public static void main(String[] args) {
        Shape s = new Circle();
        System.out.println(s.getArea(5d));
        System.out.println(calculateArea(s,5d));
        Shape s1 = new Square();
        System.out.println(calculateArea(s1,5d));
    }
    public static double calculateArea(Shape s, double d){
        if(s==null) return 0d;
        return s.getArea(d);
    }
}
class Circle implements Shape{
    public double getArea(double d){
        if(d<0) return 0d;
        return d*d*(22.0/7);
    }
}
class Square implements Shape{
    public double getArea(double d){
        //if(d<0)   return 0.0;
        return d*d;
    }
}
相关问题