Error-prone point record in the practical application of Java code

1 Create Object

I want to fight methods create different objects according to the received name, and finally call the method, which is an interface palnt these three objects already implements this interface. However, the following run-time code is wrong because I declared plant in its scope only if the {} is valid, and therefore wrong use directly back.

public void fight(String name){
   if ("Bean".equals(name)){
     Plant plant =  new Bean();
   }else if ("Ice".equals(name)){
     Plant plant =   new Ice();
    }else {
      Plant plant =  new Wall();
    }
    plant.fight();
}

The right way

     Plant plant = null;
     if ("Bean".equals(name)){
         plant =  new Bean();
     }else if ("Ice".equals(name)){
          plant =   new Ice();
      }else {
           plant =  new Wall();
      }
      plant.fight(); 

 

Guess you like

Origin www.cnblogs.com/youngao/p/11371423.html