gpt4 book ai didi

Java接口(interface)与实现类中的构造函数

转载 作者:行者123 更新时间:2023-12-01 16:33:23 27 4
gpt4 key购买 nike

我有一个关于接口(interface)的相当基本的问题,我也是个新手。我通常会使用重载的构造函数实例化我的类。我现在尝试使用接口(interface)并想知道如何填充我的构造函数。我是否可以在界面中使用类似 setSomeMethod(arguement1, argument2) 的东西来填充我的属性?

我还想指出,我正在使用带有服务注入(inject)的“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);
}

实现类

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;
}

}

提前致谢。

最佳答案

首先,您的 bicycle 方法应该使用返回类型声明:

public void someMethod(String arg1, String arg2);

接口(interface)定义了方法的契约,而不是对象的实例化方式。他们还可以定义静态变量。

要在 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
}

关于Java接口(interface)与实现类中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12023350/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com