在onCreate调用期间重新定义Java类的变量?

在onCreate调用期间重新定义Java类的变量?,java,constructor,initialization,member,Java,Constructor,Initialization,Member,我想做的是用一个新类(“Country”)扩展一个接口(ICountry),该类有一些默认值。我想知道在创建Country类的新实例时是否可以重新定义其中一些默认值。我的示例中的最后一行代码是我目前试图实现这一点的代码,但我的IDE警告我“稳定性不能解析为变量” 我的问题是,在实例化类而不构造方法时,是否可以重新定义一些对象的默认值 我刚刚开始自学Java和Android编程,所以如果你认为我提到的术语有误,请纠正我。这就是重载构造函数的用途: public class Country impl

我想做的是用一个新类(“Country”)扩展一个接口(ICountry),该类有一些默认值。我想知道在创建Country类的新实例时是否可以重新定义其中一些默认值。我的示例中的最后一行代码是我目前试图实现这一点的代码,但我的IDE警告我“稳定性不能解析为变量”

我的问题是,在实例化类而不构造方法时,是否可以重新定义一些对象的默认值


我刚刚开始自学Java和Android编程,所以如果你认为我提到的术语有误,请纠正我。

这就是重载构造函数的用途:

public class Country implements ICountry {
   int stability = 2;
}

Country poland = new Country(stability = 3);

您需要定义一个
Country
的构造函数,该构造函数接受一个参数并将其分配给一个字段,如下所示:

public Country(int stability)  
{
   this.stability=stability;
}  
然后可以创建此类的多个实例,如下所示:

public class Country implements ICountry {
   int stability = 2; // the default

   public Country() {
        // no parameters, no assignments
   }

   public Country(int stability) {
       // declares parameter, assigns to field
       this.stability = stability;
   }
}
您需要有两个构造函数的原因是,如果您没有指定一个构造函数,则会生成没有参数的版本(“默认”或“隐式”构造函数),但一旦指定了构造函数,就不会再生成它

默认构造函数的替代和等效语法可以是:

Country unitedKingdom = new Country(); // 2 is the value of stability, taken from the default
Country poland = new Country(3); // 3 is the value of stability
默认构造函数的此版本和以前版本都会产生相同的效果,但通常是首选问题

有些语言使用您所展示的语法,它们被称为“命名参数”,但Java没有

public class Country implements ICountry {
   int stability; // declare field, but don't assign a value here

   public Country() {
        this.stability = 2; // instead assign here, this is equivalent
   }
}