I'm training on Android in the field of inheritance And I want to know why the definition of the name and color variables from the final keyword - And when I remove this keyword, no use is made. And when I get this keyword, there is no error or accident - Please tell me what the reason for using the final is
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);
}
}
Cat.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();
}
}