Need help understanding casting a child object to a parent reference
I am trying to make a simple text rpg after studying java for a bit to try and solidify what I have learned so far. I was under the impression that if you make a parent(base class) reference and then calling a child(derived) class constructor that it would cast the parent to a child. To some extent I understand the process and I am able to use the child methods but only if the parent class has that method. Here is an example.
Code:
public class Item
{
private int itemLevel;
private int itemType;
public Item()
{
}
public int getItemLevel()
{
return itemLevel;
}
public void setItemLevel(int itemLevel)
{
this.itemLevel = itemLevel;
}
public int getItemType()
{
return itemType;
}
public void setItemType(int itemType)
{
this.itemType = itemType;
}
public String toString()
{
return "I'm an Item";
}
}
public class Armor extends Item
{
private String name;
private int defense;
private int equipSlot;
private int[] primaryStat;
private int[] socket;
private Enchantment enchant;
public Armor()
{
this.name = "";
this.defense = 0;
this.equipSlot = 0;
this.primaryStat = new int[0];
this.socket = new int[0];
this.enchant = new Enchantment();
}
public Armor(int level)
{
setItemType(1);
this.name = "";
this.defense = 0;
this.equipSlot = 0;
this.primaryStat = new int[0];
this.socket = new int[0];
this.enchant = new Enchantment();
}
public String toString()
{
String itemString = (name + "\n" + defense + "\n" + enchant);
return itemString;
}
public void setName(String name)
{
this.name = name;
}
public void setDefense(int defense)
{
this.defense = defense;
}
}
Now here is the part I don't understand.
Code:
Item item;
item = new Armor();
item.setDefense(1); //Doesn't work
System.out.println(item.toString()); //Prints the Armor toString instead of Item toString
So from what I understand then is that you can cast a derived class object onto a base object/ref but you can't use the derived class methods that the base class doesn't have. I wanted to make an array of Item references as an inventory that can hold the derived classes objects but it looks like I am going about the concept wrong. Can anyone help explain this concept?