我想以一种方式使用java接口,我将在其他类中调用定义接口,例如私有SoapURL soapURL;'而且我可以访问任何类的方法,例如:我想使用登录: -
private SoapURL soapURL;
SoapUrl = LoginSoap ();
String nameSpace = soapURL.getMethodName();
String url = soapURL.getUrl();
有没有办法做这样的事情。对不起,我对面向对象的原则不是很了解,但如果我的问题有解决方案,我想知道。提前谢谢。
public interface SoapURL {
public String getNameSpace();
public String getUrl();
public String getSoapAction();
public String getMethodName();
public String getTag();
}
LoginSoap类
public class LoginSoap implements SoapURL {
@Override
public String getNameSpace() {
return "https://host.com/MobileWFC/";
}
@Override
public String getUrl() {
return "https://host.com/MobileWFC/MobileWS.asmx";
}
@Override
public String getSoapAction() {
return "https://host.com/MobileWFC/UserControl";
}
@Override
public String getMethodName() {
return "UserControl";
}
@Override
public String getTag() {
return "Login Activity";
}
}
SignUpSoap类
public class SignUpSoap implements SoapURL {
@Override
public String getNameSpace() {
return "https://host.com/MobileWFC/";
}
@Override
public String getUrl() {
return "https://host.com/MobileWFC/MobileWS.asmx";
}
@Override
public String getSoapAction() {
return "https://host.com/MobileWFC/UserRegister";
}
@Override
public String getMethodName() {
return "UserRegister";
}
@Override
public String getTag() {
return "SignUp Activity";
}
}
ResetPasswordSoap类
public class ResetPasswordSoap implements SoapURL {
@Override
public String getNameSpace() {
return "https://host.com/MobileWFC/";
}
@Override
public String getUrl() {
return "https://host.com/MobileWFC/MobileWS.asmx";
}
@Override
public String getSoapAction() {
return "https://host.com/MobileWFC/UserPasswordReset";
}
@Override
public String getMethodName() {
return "UserPasswordReset";
}
@Override
public String getTag() {
return "Forget Password Activity";
}
}
答案 0 :(得分:1)
就这样做,例如:
SoapURL example = new LoginSoap();
String a = example.getTag();
a
应该等于"Login Activity"
答案 1 :(得分:1)
您的实施看起来是正确的。要使用它,您可以在main中执行此操作:
SoapURL reset = new ResetPasswordSoap();
System.out.println(reset.getUrl());
这是一种在大型系统中最小化耦合的方法。并通过为一起工作的对象组使用公共接口来减少对象之间的依赖关系。你可能是面向对象原则的新手,但你已经领先于游戏
要将其传递给函数,请执行以下操作:
public JPanel resetPass(SoapURL reset) {
...
}
// In main:
JPanel resetPassPanel = resetPass(reset);
答案 2 :(得分:1)
接口的主要用途是 多态 ,或执行相同的功能 对许多不同的物体进行操作, 这正是你想要的场景
您的方法绝对正确,只需要进行修改
private SoapURL soapURL;
//SoapUrl = LoginSoap (); // This line should be replaced with the Below line
soapURL=new LoginSoap();
String nameSpace = soapURL.getMethodName();
String url = soapURL.getUrl();
由于LoginSoap
,SignUpSoap
,ResetPasswordSoap
类是SoapURL Interface
的实现类,因此SoapURL的引用变量可以存储任何这些子类的Object
soapURL=new LoginSoap();//soapURL.someMethod will call method of LoginSoapClass
soapURL=new SignUpSoap();// will call method of SignUpSoap class
soapURL=new ResetPasswordSoap();