I have two abstract classes: Char and Weapon. Each has two derivative classes: King and Troll, and Club and Sword.
A character always has a weapon, but the type is not specified. So when building the Char class I cannot initialise the correct type. Also, when choosing a character, I similarly cannot initialise the correct type.
Is it wrong to initialise an abstract class? How can one initialise a class of one sort and then change the variable class? Provided the new type is a trivially different inheritation of the same parent class? Or should one go about it completely differently?
It may very well be that I haven't even understood the concept of an abstract class. I'm new to Java and pure OOP.
public class Player{
private Char c; // Wrong?
public void changeChar(int charID, int wepID){
switch(charID){
case 1: c = new King(wepID); break;
case 2: c = new Troll(wepID); break;
}
}
public void fight(){
c.fight();
}
}
abstract class Char{
protected String name;
public Weapon weapon; // Wrong?
Char(int wepID){
switch(wepID){
case 1: weapon = new Sword(); break;
case 2: weapon = new Club(); break;
}
}
public void fight(){
weapon.useWeapon(name);
}
}
abstract class Weapon{
protected String wepName;
public void useWeapon(String user){
System.out.println(user + " fights with " + wepName);
}
}
class Club extends Weapon{
Club(){
wepName = "Club";
}
}
class Sword extends Weapon{
Sword(){
wepName = "Sword";
}
}
class Troll extends Char{
Troll(int wepID){
super(wepID);
name = "Troll";
}
}
class King extends Char{
King(int wepID){
super(wepID);
name = "King";
}
}