我对接口有一个相当基本的问题,我也很新。我通常会使用重载的构造函数实例化我的类。我现在正在尝试使用接口,并想知道如何填充我的构造函数。我会在界面中使用类似setSomeMethod(arguement1,arguement2)的东西来填充我的属性吗?
我还想注意我正在使用带有服务注入的“Tapestry5”框架。实施例
public class Main {
@Inject
private Bicycle bicycle;
public Main() {
//Not sure how to pass constructor variables in
this.bicycle();
}
}
接口
public interface bicycle {
public void someMethod(String arg1, String arg2);
}
Impl Class
public class MountainBike implements bicycle {
private String arg1;
private String arg2;
public MountainBike() {
//Assuming there is no way to overload this constructor
}
public void someMethod(String arg1, String2 arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
}
}
那么你如何处理扩展类?我不知道如何填充扩展类构造函数。
public class MountainBike extends BicycleParts implements bicycle {
private String arg1;
private String arg2;
public MountainBike() {
//Assuming there is no way to overload this constructor
//Not sure where to put super either, but clearly won't work here.
//super(arg1);
}
public void someMethod(String arg1, String2 arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
//Assuming it doesn't work outside of a constructor, so shouldn't work
//here either.
//super(arg1);
}
}
public class BicycleParts {
private String arg1;
public void BicycleParts(String arg1) {
this.arg1 = arg1;
}
}
提前致谢。
答案 0 :(得分:4)
首先,您的bicycle
方法应使用返回类型声明:
public void someMethod(String arg1, String arg2);
接口定义方法的契约,而不是如何实例化对象。他们还可以定义静态变量。
要在MountainBike构造函数中使用someMethod
,您可以在构造函数中进行调用:
public MountainBike(String arg1, String arg2) {
someMethod(arg1, arg2);
}
Wrt,关于扩展类的问题,super语句必须作为构造函数中的第一个语句出现,即:
public class MegaMountainBike extends BicycleParts implements bicycle {
public MegaMountainBike() {
super("Comfy Saddle");
// do other stuff
}
答案 1 :(得分:2)
new
语句,就会隐式调用它们。由于构造函数不能放在接口中,因此通常的做法是使用工厂方法。