【发布时间】:2019-06-13 04:51:56
【问题描述】:
我在继承领域培训Android 我想知道为什么从final关键字定义名称和颜色变量 - 当我删除这个关键字时,没有任何用处。当我得到这个关键字时,没有错误或意外 - 请告诉我使用final的原因是什么
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtAnimal = (TextView) findViewById(R.id.txtAnimal);
TextView txtCat = (TextView) findViewById(R.id.txtCat);
Animal animal1 = new Animal("tiger", "orange", 60, 80);
Cat cat1 = new Cat("persian", "brown", 40, 25, 4, true);
txtAnimal.setText(animal1.toString());
txtCat.setText(cat1.toString());
}
Animal.java
public class Animal extends Object{
private final String name;
private final String color;
private int amountOfSpeed;
private int amountOfPower;
public Animal(String name, String color, int amountOfSpeed, int amountOfPower){
// this. for same name
this.name = name;
this.color = color;
this.amountOfSpeed = amountOfSpeed;
this.amountOfPower = amountOfPower;
}
// we can use setter because variable (name-color) are defined final
public String getName(){
return name;
}
public String getColor(){
return color;
}
public void setAmountOfSpeed(int amountOfSpeed){
this.amountOfSpeed = amountOfSpeed;
}
public int getAmountOfSpeed(){
return amountOfSpeed;
}
public void setAmountOfPower(int amountOfPower){
this.amountOfPower = amountOfPower;
}
public int getAmountOfPower(){
return amountOfPower;
}
public int evaluateAnimalValue(){
int result = amountOfSpeed *amountOfPower;
return result;
}
@Override
public String toString() {
return String.format("%s: %s %s: %s %s: %d %s: %d",
"Name", name,
"Color", color,
"Speed", amountOfSpeed,
"Power", amountOfPower);
}
}
猫.java
private final int numberOfLegs;
private boolean canHuntOtherAnimal;
public Cat(String name, String color, int amountOfSpeed, int amountOfPower, int numberOfLegs, boolean canHuntOtherAnimal){
super(name, color, amountOfSpeed, amountOfPower);
this.numberOfLegs = numberOfLegs;
this.canHuntOtherAnimal = canHuntOtherAnimal;
}
public int getNumberOfLegs() {
return numberOfLegs;
}
public boolean getCanHuntOtherAnimal() {
return canHuntOtherAnimal;
}
public void setCanHuntOtherAnimal(boolean canHuntOtherAnimal) {
this.canHuntOtherAnimal = canHuntOtherAnimal;
}
@Override
public String toString() {
return super.toString() + String.format(" %s: %d %s: %b",
"Legs", numberOfLegs,
"Fight", canHuntOtherAnimal) + " Animal Value: " + evaluateAnimalValue();
}
}
【问题讨论】:
-
document 和 enforce 值是不可变的,即在构造函数中赋值后无法更改。
-
@Andreas 如果不是final,在构造函数中怎么改?继承可以改变的任何类?
-
@Andreas 这是 IMO 的最佳理由。如果你看到一些被宣布为最终的东西,你(通常)应该对自己说“嘿,也许我不应该试图编辑它”。尽管已经无法从课堂外进行编辑,但将其声明为 final 可以让您在课堂内更加安全,以防止发生意外。
标签: java android inheritance