Object Instances
You do not create copies of created instances . The semantics of copy is to create a completely separate but identical instance pre-existing instance . This is also called clone in Java incorrectly due to the semantics of the term clone .
Idiomatic creation
final Character character; // assuming that all the instances subclass `Character` if ("warrior".equalsIgnoresCase(playerClass)) { character= new Warrior(); } else if ("cleric".equalsIgnoresCase(playerClass)) { character = new Cleric(); } else if ( /* you get the idea */ ) { character= new Whatever();} else() { throw new RuntimeException(playerClass + " is not a valid class"); }
Learning how to use final is paramount to writing, easy to maintain deterministic code.
It is important that all if/else if/else are exclusive, so there are no cases that you missed. It is never that character was null or was not correctly initialized with this code.
Idiom "SomeString".equalsIgnoreCase(variable); comparing a String literal with a variable ensures that you never have to test null and will not get a NullPointerException during the comparison, because null already inside the method.
It also avoids the use of null , which almost never works and leads to a large number of security programs and it is difficult to maintain code. You either create a valid instance, or you fail, and know exactly why this failed.
Having a character instance named player confused.
It must be a Factory method template.
public Character characterFromClass(@Nonnull final String characterClass) { if ("warrior".equalsIgnoreCase(characterClass)) { return new Warrior(); } else if ("cleric".equalsIgnoreCase(characterClass)) { return = new Cleric(); } else if ( ) { return new Whatever();} else() { throw new RuntimeException(characterClass+ " is not a valid class"); } } final Character character = characterFromClass(input.nextLine());
This is just one of the Creation templates available to you.
source share