I am trying to select a specific subclass based on the user input, but I'm not quite sure how to do this. For example:
System.out.println("Select animal:\n1. Cat\n2. Dog");
int input = keyboard.nextInt();
if(input == 1){
Cat newPet = new Cat();
}
else{
Dog newPet = new Dog();
}
This is just a quick example I created just now, so excuse any syntax errors. I understand that once the if statement is over, the newPet object is out of scope so it can no longer be used afterwards. I also tried cases but this does not work, since I am declaring newPet twice, even though only one can be accessed in every run of the program.
Depending on the user input, multiple different factors further down in the program would be affected. I could always use an if statement in each of the different factors, but was wondering if theres a cleaner way to do this?
Aucun commentaire:
Enregistrer un commentaire