我是Java的新手,我有以下代码,并且像
一样获得异常Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type Calculator2Service
The method getCalculator2Port() is undefined for the type Calculator2Service
at com.theopentutorials.ws.calc2.client.Calc2Client.main(Calc2Client.java:13)
请一位帮助..
package com.theopentutorials.ws.calc2.client;
import com.theopentutorials.ws.calc2.*;
public class Calc2Client {
/**
* @param args
*/
public static void main(String[] args) {
int a = 10;
int b = 12;
Calculator2Service calcService = new Calculator2Service();
Calculator2 calc = calcService.getCalculator2Port();
System.out.println(a + " + " + b + " = " + calc.add(a, b));
System.out.println(a + " - " + b + " = " + calc.sub(a, b));
}
}
答案 0 :(得分:0)
您应该在班级getCalculator2Port
中定义Calculator2Service
。如果您确定已经完成了这项工作,请检查拼写并注意Java是一种区分大小写的语言。
顺便说一下,您可能希望访问getCalculator2Port
,但在此范围内不可见,例如它是private
方法,但在这种情况下,您会收到通知“方法......来自类型......不可见”。
答案 1 :(得分:0)
Calculator2Port是一个工厂方法,它在这里返回一个Calculator2对象。您应该定义一个接口或抽象类,如
public interface Calculator2 {
public double add(double a, double b);
public double sub(double a, double b);
}
然后在Calculator2Service中应该有一个类似
的方法Calculator2 getCalculator2Port(){
Calculator2 c = new Calculator2(){
public double add(double a,double b){
return(a+b);
}
public double sub (double a, double b){
return(a-b);
}
}
return(c);
}