内部类更改外部变量java
我在我的项目中使用Vaadin,我有一个问题:如何更改变量外部类franchSize内部类更改外部变量java,java,class,vaadin,Java,Class,Vaadin,我在我的项目中使用Vaadin,我有一个问题:如何更改变量外部类franchSize TextField franchSize = new TextField(); franchSize.setDebugId("franch_size"); hl1.addComponent(franchSize); franchSize.setValue("0");
TextField franchSize = new TextField();
franchSize.setDebugId("franch_size");
hl1.addComponent(franchSize);
franchSize.setValue("0");
hl1.setComponentAlignment(franchSize,
Alignment.MIDDLE_CENTER);
franchSize.addListener(new Property.ValueChangeListener() {
private static final long defaultValue = 0;
public void valueChange(ValueChangeEvent event) {
String value = (String) event.getProperty().getValue();
if(Integer.valueOf(value)%1==0){
franchSize.setValue("0");
franchSize.getWindow().showNotification("","Bla-bla-bla",Notification.TYPE_HUMANIZED_MESSAGE);
}
}
});
错误:无法在franchSize.setValue0中的不同方法中定义的内部类中引用非最终变量franchSize;和franchSize.getWindow.showNotification,blablablabla,Notification.TYPE_人性化_消息 将franchSize设置为final(如错误消息中所述),或使用TextFieldevent.getSource而不是引用外部变量
关于错误的信息这里的错误非常清楚:如果不将外部变量设置为final,就无法访问内部类中的外部变量。所以只需在TextField前面添加final franchSize=newtextfield 下面是一个与外部类变量通信的简单实现
public class Google01 implements Outer{
// outer class variable, see no final here
int outer = 0;
public static void main(String[] args) {
Google01 inst = new Google01();
inst.testMe();
}
public void testMe(){
// Inner class
class temp{
Outer out;
public temp(Outer out) {
this.out = out;
}
public void printMe(String text){
// reading outer variable
System.out.println(out.getValue() + text);
// setting outer variable
out.setValue(out.getValue() + 1);
}
}
// Lets start our test
temp obj = new temp(this);
System.out.println("Value of outer before call = " + outer);
// this should increment outer value, see number before Yahoo in output
obj.printMe("Yahooo");
obj.printMe("Google");
obj.printMe("Bing");
// Lets print outer value directly.
System.out.println("Value of outer after call = " + outer);
}
@Override
public void setValue(int value) {
outer = value;
}
@Override
public int getValue() {
return outer;
}
}
// An interface that is use to communicate with outer class variable.
interface Outer{
void setValue(int value);
int getValue();
}
输出
简要说明:
你需要制作一个接口来与外部类进行通信我喜欢制作用于通信的接口,但也可以使用传递外部类实例来完成,而不是制作一个全新的接口,并且你可以使用接口提供的实用方法来获取或将值放入外部类中。
您可以参考了解错误发生的原因。
在这个场景中,我唯一改变的是,我将变量作为类级变量成员变量,而不是方法变量。只需在外部类中创建一个私有字段“TextField franchSize”。
那么,访问它的最佳方法就是使用受保护的getter。您不只是将变量传递到内部类中吗?他/她也可以通过传递franchSize来完成同样的操作吗?另外,TextField是一个vaadin类,如果该值已经来自两个源,那么再次包装它就太过分了。是的,我只是传递变量,因为我们不能在内部类中直接使用外部变量。
Value of outer before call = 0
0Yahooo
1Google
2Bing
Value of outer after call = 3