gpt4 book ai didi

java - 静态方法中的默认变量

转载 作者:行者123 更新时间:2023-12-02 11:03:12 25 4
gpt4 key购买 nike

我有一个方法(例如helpMethod)出现在我的许多项目类中,并使用所有这些类中作为私有(private)类属性存在的变量(例如xVar)执行某些操作。我想在默认类中将此方法设为静态并从那里使用它。是否可以避免必须将 xVar 作为参数传递给静态实现?

类似于:

class helpClass {
static void helpMethod() {
return ++xVar;
}
}

class demoClass {
private int xVar = 0;

int addToXVar() {
helpClass.helpMethod();
}
}

而不是:

class helpClass {
static void helpMethod(int xVar) {
return ++xVar;
}
}

class demoClass {
private int xVar = 0;

int addToXVar() {
helpClass.helpMethod(xVar);
}
}

最佳答案

为了避免必须传递对 demoClass 的引用,您可以做的就是使用父类(super class)。

class helpClass {
protected int xVar = 0;

void helpMethod() {
++xVar;
}
}

class demoClass extends helpClass {

int addToXVar() {
helpMethod();
}
}

或者您可以使用 Java 8+ 中的接口(interface)

interface helper {
int getXVar();
void setXVar(int xVar);

default void helpMethod() {
setXVar(1 + getXVar());
}
}

class demoClass implements helpClass {
private int xVar = 0;

int addToXVar() {
helpMethod();
}

public int getXVar() { return xVar; }
public void setXVar(int xVar) { this.xVar = xVar; }
}

关于java - 静态方法中的默认变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51176882/

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