Android Studio 静态或非静态变量和方法
Android Studio static or non-static variables and methods
我对什么时候变量或方法应该是静态的感到有点困惑。我开发了一个包含多个 类、变量和方法的应用程序,并且很少使用关键字 static。然而,它的工作令人满意。如果我犯了错误,你能告诉我吗?为什么?这是我的代码示例:
public class GameActivity extends AppCompatActivity {
public String[] mots = {"AFTERNOON", "AIRPORT","AVENUE","BETWEEN", "BUS", "CAB", "COAST","DAY",
"DIFFERENCE","DOLLARS","ENGLISH","FRENCH","GOOD","GOODBYE","HOUR","IMPROVE","LATER",
"LOCAL","MARGARET","NAME","NINE","NUMBER","ONLY","PHONE","PLANE","SAME","SHARE",
"SIDEWALK","STATES","SUNDAY","THERE","TIME","TWELVE","UNITED","UNIVERSITY","VERY",
"WEST","WHEN","WOMAN","YOUNG"};
public String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
public String mysteryWord = "vide";
//public int nombreDeLettres;
public int numeroImage = 1;
public boolean jeuFini = false;
public int lettresDevinees = 0;
public int wins = 0;
public int losses = 0;
public int numberOfMots;
int numeroAuHasard;
public Boolean maLettreAServi = false;
public ArrayList<CharSequence> lettresEssayees = new ArrayList<>();
public Button monBouton;
public TextView monTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder()
.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4") // adds my test phone
.build();
mAdView.loadAd(request);
// une des solutions pour rendre la zone trado scrollable
TextView myXmlContent = (TextView)findViewById(R.id.zone_trado_scrollable);
myXmlContent.setMovementMethod(new ScrollingMovementMethod());
// écouteurs de tous les boutons actifs
ecouteursDeBoutons();
}
// joue une lettre
public void playLetter(final String letter) {
Resources res = getResources();
final int resId = res.getIdentifier(letter, "id", getPackageName());
monTextView = (TextView) this.findViewById(R.id.zone_trado_scrollable);
final TextView maLettre = (TextView) this.findViewById(resId);
maLettre.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!jeuFini) { // il faut mettre ce test _dans_ le onClick(View v)
if (!mysteryWord.equalsIgnoreCase("vide")) {
if (!lettresEssayees.contains(maLettre.getText())) {
// on teste que la lettre n'a pas déjà été essayée
maLettreAServi = false;
// boucle de test de lettre
for (int i = 0; i < mysteryWord.length(); i++) {
if (String.valueOf(mysteryWord.charAt(i)).equals(maLettre.getText())) {
int j = i + 1; // car dans le layout xml les id des positions commencent à 1
//monTextView.append("\nyou correctly found " + maLettre.getText() + " at position " + j);
final int resId = getResources().getIdentifier("position" + j, "id", getPackageName());
final TextView lettreADeviner = (TextView) GameActivity.this.findViewById(resId);
lettreADeviner.setText(maLettre.getText());
maLettreAServi = true;
lettresDevinees++;
}
}
maLettre.setText(""); // on efface de l'alphabet la lettre essayée
lettresEssayees.add(maLettre.getText());
// on la met dans l'arraylist lettresEssayees
// afin de ne pas la réessayer
// noter que java comprend qu'il s'agit d'un caractère et non d'une string
// test pour effacer de l'alphabet une lettre qui a servi
if (!maLettreAServi) {
// incrémenter le pendu
numeroImage++;
if (numeroImage < 10) {
ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
final int imageId = getResources().getIdentifier("pendu" + numeroImage, "drawable", getPackageName());
monImage.setImageResource(imageId);
} else {
ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
final int imageId = getResources().getIdentifier("pendu10", "drawable", getPackageName());
monImage.setImageResource(imageId);
jeuFini = true;
monTextView.setText(Html.fromHtml("<font color=\"red\">you lost</font>"));
monTextView.append("\nthe word was "+mysteryWord);
losses++;
TextView nombrePertes = (TextView) findViewById(R.id.nr_losses);
nombrePertes.setText("" + losses); // pas réussi à utiliser toString(), alors j'utilise cette converstion
}
}
// test qu'on a trouvé le mot mystère
if (lettresDevinees == mysteryWord.length()) {
jeuFini = true;
// randomisation des félicitations
Random generator = new Random();
int randomIndex = generator.nextInt(3);
if(randomIndex == 0){
monTextView.setText(Html.fromHtml("<font color=\"blue\">bravo!</font>"));}
else if(randomIndex == 1){
monTextView.setText(Html.fromHtml("<font color=\"blue\">fantastic!</font>"));}
else if (randomIndex == 2) {
monTextView.setText(Html.fromHtml("<font color=\"blue\">you won</font>"));}
// rappel de ce qu'était le mot à deviner
monTextView.append("\nthe word was indeed " + mysteryWord);
String son = mysteryWord.toLowerCase()+"1";
final int resRaw = getResources().getIdentifier(son, "raw", getPackageName());
final MediaPlayer mp = MediaPlayer.create(GameActivity.this, resRaw);
mp.start();
wins++;
TextView nombreGains = (TextView) findViewById(R.id.nr_wins);
nombreGains.setText("" + wins); // pas réussi à utiliser toString(), alors j'utilise cette converstion
}
}
} else {
monTextView.setText("click on Select word first");
}
}
}
});
}
...
}
如果您希望在整个 class 中仅共享变量或方法的单个副本而不创建不同的副本,则应使用 static.. 并且接口变量默认为静态和最终的。如果你想了解更多
,你应该先学习基本JAVA概念
静态变量可以直接使用其 class 名称访问,并且它只有一个实例。
YourActivity.staticVariableName=something;
这有助于从应用程序的任何位置访问变量。但要注意它有一个生命周期,直到你的整个应用程序结束。因此它会在整个应用程序生命周期内消耗该内存。因此请牢记这一点来使用它。
java中的static关键字主要用于内存管理。我们可以将 java static 关键字应用于变量、方法、块和嵌套 class。
如果我们谈论静态变量,那么我们将其定义为
静态变量可用于引用所有对象的公共 属性(每个对象都不是唯一的),例如员工公司名称、学生所在院校名称等
静态变量在class加载时只在class区域获取一次内存。
如果我们谈论它使用:
当你想在整个 class 中只共享你的变量或方法的单个副本而不创建不同的副本时,你应该使用 static.
优势
它使您的程序内存高效(即节省内存)。
一般来说,所有未绑定到 class 对象且适用于整个对象的常量和变量都应声明为静态的。因此,查看您的示例代码,您应该将 mots
、alphabet
声明为 static
和 final
,因为没有必要为您的 class。
此外,关键字 static 还允许您从其他 classes 访问这些常量,如果您想使用它们,也只需使用 class 名称 GameActivity
,例如 GameActivity.mots
其他地方和 final
关键字向您保证没有人可以更改这些。
public final static String[] mots = {"AFTERNOON", "AIRPORT","AVENUE","BETWEEN", "BUS", "CAB", "COAST","DAY",
"DIFFERENCE","DOLLARS","ENGLISH","FRENCH","GOOD","GOODBYE","HOUR","IMPROVE","LATER",
"LOCAL","MARGARET","NAME","NINE","NUMBER","ONLY","PHONE","PLANE","SAME","SHARE",
"SIDEWALK","STATES","SUNDAY","THERE","TIME","TWELVE","UNITED","UNIVERSITY","VERY",
"WEST","WHEN","WOMAN","YOUNG"};
public final String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
static 变量基本上是当你想在你的应用程序中使用多个地方的单个变量时使用的。类似静态方法的概念。
如需更多信息,请关注此 link
http://www.javatpoint.com/static-keyword-in-java
我只想在 pgiitu 和 Piyush Gupta 的回答中再补充一点。
根据 Java docs:
如果您的变量存储常量值,例如 static final int NUM_GEARS = 6,则约定会略有变化,将每个字母大写,并使用下划线字符分隔后续单词。按照惯例,下划线字符从不在其他地方使用。
因此,正如pgiitu提到的mots
和alphabet
应该声明为static
和final
。但是,按照命名约定,您应该将它们分别重命名为 MOTS
和 ALPHABET
。
我对什么时候变量或方法应该是静态的感到有点困惑。我开发了一个包含多个 类、变量和方法的应用程序,并且很少使用关键字 static。然而,它的工作令人满意。如果我犯了错误,你能告诉我吗?为什么?这是我的代码示例:
public class GameActivity extends AppCompatActivity {
public String[] mots = {"AFTERNOON", "AIRPORT","AVENUE","BETWEEN", "BUS", "CAB", "COAST","DAY",
"DIFFERENCE","DOLLARS","ENGLISH","FRENCH","GOOD","GOODBYE","HOUR","IMPROVE","LATER",
"LOCAL","MARGARET","NAME","NINE","NUMBER","ONLY","PHONE","PLANE","SAME","SHARE",
"SIDEWALK","STATES","SUNDAY","THERE","TIME","TWELVE","UNITED","UNIVERSITY","VERY",
"WEST","WHEN","WOMAN","YOUNG"};
public String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
public String mysteryWord = "vide";
//public int nombreDeLettres;
public int numeroImage = 1;
public boolean jeuFini = false;
public int lettresDevinees = 0;
public int wins = 0;
public int losses = 0;
public int numberOfMots;
int numeroAuHasard;
public Boolean maLettreAServi = false;
public ArrayList<CharSequence> lettresEssayees = new ArrayList<>();
public Button monBouton;
public TextView monTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder()
.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4") // adds my test phone
.build();
mAdView.loadAd(request);
// une des solutions pour rendre la zone trado scrollable
TextView myXmlContent = (TextView)findViewById(R.id.zone_trado_scrollable);
myXmlContent.setMovementMethod(new ScrollingMovementMethod());
// écouteurs de tous les boutons actifs
ecouteursDeBoutons();
}
// joue une lettre
public void playLetter(final String letter) {
Resources res = getResources();
final int resId = res.getIdentifier(letter, "id", getPackageName());
monTextView = (TextView) this.findViewById(R.id.zone_trado_scrollable);
final TextView maLettre = (TextView) this.findViewById(resId);
maLettre.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!jeuFini) { // il faut mettre ce test _dans_ le onClick(View v)
if (!mysteryWord.equalsIgnoreCase("vide")) {
if (!lettresEssayees.contains(maLettre.getText())) {
// on teste que la lettre n'a pas déjà été essayée
maLettreAServi = false;
// boucle de test de lettre
for (int i = 0; i < mysteryWord.length(); i++) {
if (String.valueOf(mysteryWord.charAt(i)).equals(maLettre.getText())) {
int j = i + 1; // car dans le layout xml les id des positions commencent à 1
//monTextView.append("\nyou correctly found " + maLettre.getText() + " at position " + j);
final int resId = getResources().getIdentifier("position" + j, "id", getPackageName());
final TextView lettreADeviner = (TextView) GameActivity.this.findViewById(resId);
lettreADeviner.setText(maLettre.getText());
maLettreAServi = true;
lettresDevinees++;
}
}
maLettre.setText(""); // on efface de l'alphabet la lettre essayée
lettresEssayees.add(maLettre.getText());
// on la met dans l'arraylist lettresEssayees
// afin de ne pas la réessayer
// noter que java comprend qu'il s'agit d'un caractère et non d'une string
// test pour effacer de l'alphabet une lettre qui a servi
if (!maLettreAServi) {
// incrémenter le pendu
numeroImage++;
if (numeroImage < 10) {
ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
final int imageId = getResources().getIdentifier("pendu" + numeroImage, "drawable", getPackageName());
monImage.setImageResource(imageId);
} else {
ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
final int imageId = getResources().getIdentifier("pendu10", "drawable", getPackageName());
monImage.setImageResource(imageId);
jeuFini = true;
monTextView.setText(Html.fromHtml("<font color=\"red\">you lost</font>"));
monTextView.append("\nthe word was "+mysteryWord);
losses++;
TextView nombrePertes = (TextView) findViewById(R.id.nr_losses);
nombrePertes.setText("" + losses); // pas réussi à utiliser toString(), alors j'utilise cette converstion
}
}
// test qu'on a trouvé le mot mystère
if (lettresDevinees == mysteryWord.length()) {
jeuFini = true;
// randomisation des félicitations
Random generator = new Random();
int randomIndex = generator.nextInt(3);
if(randomIndex == 0){
monTextView.setText(Html.fromHtml("<font color=\"blue\">bravo!</font>"));}
else if(randomIndex == 1){
monTextView.setText(Html.fromHtml("<font color=\"blue\">fantastic!</font>"));}
else if (randomIndex == 2) {
monTextView.setText(Html.fromHtml("<font color=\"blue\">you won</font>"));}
// rappel de ce qu'était le mot à deviner
monTextView.append("\nthe word was indeed " + mysteryWord);
String son = mysteryWord.toLowerCase()+"1";
final int resRaw = getResources().getIdentifier(son, "raw", getPackageName());
final MediaPlayer mp = MediaPlayer.create(GameActivity.this, resRaw);
mp.start();
wins++;
TextView nombreGains = (TextView) findViewById(R.id.nr_wins);
nombreGains.setText("" + wins); // pas réussi à utiliser toString(), alors j'utilise cette converstion
}
}
} else {
monTextView.setText("click on Select word first");
}
}
}
});
}
...
}
如果您希望在整个 class 中仅共享变量或方法的单个副本而不创建不同的副本,则应使用 static.. 并且接口变量默认为静态和最终的。如果你想了解更多
,你应该先学习基本JAVA概念静态变量可以直接使用其 class 名称访问,并且它只有一个实例。
YourActivity.staticVariableName=something;
这有助于从应用程序的任何位置访问变量。但要注意它有一个生命周期,直到你的整个应用程序结束。因此它会在整个应用程序生命周期内消耗该内存。因此请牢记这一点来使用它。
java中的static关键字主要用于内存管理。我们可以将 java static 关键字应用于变量、方法、块和嵌套 class。 如果我们谈论静态变量,那么我们将其定义为 静态变量可用于引用所有对象的公共 属性(每个对象都不是唯一的),例如员工公司名称、学生所在院校名称等
静态变量在class加载时只在class区域获取一次内存。
如果我们谈论它使用: 当你想在整个 class 中只共享你的变量或方法的单个副本而不创建不同的副本时,你应该使用 static.
优势 它使您的程序内存高效(即节省内存)。
一般来说,所有未绑定到 class 对象且适用于整个对象的常量和变量都应声明为静态的。因此,查看您的示例代码,您应该将 mots
、alphabet
声明为 static
和 final
,因为没有必要为您的 class。
此外,关键字 static 还允许您从其他 classes 访问这些常量,如果您想使用它们,也只需使用 class 名称 GameActivity
,例如 GameActivity.mots
其他地方和 final
关键字向您保证没有人可以更改这些。
public final static String[] mots = {"AFTERNOON", "AIRPORT","AVENUE","BETWEEN", "BUS", "CAB", "COAST","DAY",
"DIFFERENCE","DOLLARS","ENGLISH","FRENCH","GOOD","GOODBYE","HOUR","IMPROVE","LATER",
"LOCAL","MARGARET","NAME","NINE","NUMBER","ONLY","PHONE","PLANE","SAME","SHARE",
"SIDEWALK","STATES","SUNDAY","THERE","TIME","TWELVE","UNITED","UNIVERSITY","VERY",
"WEST","WHEN","WOMAN","YOUNG"};
public final String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
static 变量基本上是当你想在你的应用程序中使用多个地方的单个变量时使用的。类似静态方法的概念。 如需更多信息,请关注此 link http://www.javatpoint.com/static-keyword-in-java
我只想在 pgiitu 和 Piyush Gupta 的回答中再补充一点。
根据 Java docs: 如果您的变量存储常量值,例如 static final int NUM_GEARS = 6,则约定会略有变化,将每个字母大写,并使用下划线字符分隔后续单词。按照惯例,下划线字符从不在其他地方使用。
因此,正如pgiitu提到的mots
和alphabet
应该声明为static
和final
。但是,按照命名约定,您应该将它们分别重命名为 MOTS
和 ALPHABET
。