开发者

java interfaces... quick questions

can you tell me how this line works.... my OperatorFactory.get("add") is not doing anything. I'm not getting anything printed

ArithmeticOperator add = OperatorFactory.get ("add");

when I have the following:

interface ArithmeticOperator {

    // Returns the result of applying the operator to operands a and b.
    double operate (double a, double b);

    // Return a String that is the name of this operator.
    String printName ();
}


public class OperatorFactory implements ArithmeticOperator {



    public OperatorFactory(){

    }

    public static ArithmeticOperator get(String name){
        if(name.equals("add"))
                return new PlusOperator();
        else if(name.equals("sub"))
                return new SubOperator();
        else if(name.equals("mult"))
                return new MultOperator();
        else if(name.equals("div"))
                return new DivOperator();
        else
            return null;
    }

    public double operate(double a, double b) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public String printName() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}

public class PlusOperator extends OperatorFactory {



    public double operate(double a, double b) {
        return a + b;

    }

    public String printName() {
        return "Add";
    }

}




public class PlusOperator extends OperatorFactory {



    public double operate(double a, double b) {
        return a + b;

    }

    public String printName() {
       开发者_如何学JAVA return "Add";
    }

}


You never call add.printName(), and you certainly don't output anything, so I'm not surprised that nothing is being printed.


Have you actually tried printing the name?

ArithmeticOperator add = OperatorFactory.get ("add");
System.out.println(add.printName());

Also, the PlusOperator should implement ArithmeticOperator directly. The Factory should not implement ArithmeticOperator. This allows you to remove the operate and printName methods from the factory class.


Doesn't look like your get() method calls printName(), so it shouldn't print anything.


You should call add.printName() if you would like to output the operator's name.


I won't repeat what everyone else already said - instead, here's a couple things to try in the future if you have this problem.

A good first sanity check for this problem is to run your code in a code coverage tool (I use EclEmma in Eclipse - I'm sure there's other good ones out there). This would show you that nothing is getting printed because the printName() method isn't being called.

Another way to debug this in Eclipse is by right clicking on your source, choosing "References > Project." This will show you from where the printName() method is being called, and you will see that it isn't being called because it isn't referenced from anywhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜