I am trying to figure out how to use an object's methods when iterating through an ArrayList. However, there is a part of the question that I couldn't fit above, and it's that in the ArrayList, there are objects, lets call them Shoes, that inherit from, lets say Clothes. But there are also Shirts and Socks in this array, that also each inherit from Clothes. So the array is of type Clothes, in order to accommodate the different types of objects in it. Observe:
ArrayList<Clothes> list = new ArrayList<Clothes>();
list.add(shoe);
list.add(shirt);
list.add(sock);
And this works because they all inherit from Clothes. However, I am trying to iterate through this ArrayList and use each object's unique methods like so:
for(Clothes piece : list) {
...//something like piece.getShoeSize();
}
Say I wanted to print out the shoes' sizes when a button is pressed, or the colors of each of the socks when a different button is pressed. I am unable to do this because, in the for loop itself, it is only looking for things that are of type Clothes, but when I change Clothes to Shoes, it doesn't work either, because list is a list of type Clothes. I've tried casting piece as a shoe or shirt, depending on the result of the if-statement
if(piece instanceof Shoe) {
...//((Shoe) piece).getShoeSize();
}
But that doesn't work either. If you have any ideas, I would greatly appreciate the help.
EDIT: For clarity.
Here is the class hierarchy:
public class Clothes {
getColor();
}
public class Sock extends Clothes {
...
}
public class Shirt extends Clothes {
getSize();
}
public class Shoe extends Clothes {
getSize();
}
So my program has a JComboBox with various things inside it. It also has a JTextArea beneath it. What I am trying to get my program to do is print out something into the JTextArea depending on what option is selected in the JComboBox. So let's say there is an option SIZE in the JComboBox. When it is selected, I want all of the objects that are in list, that are also capable of performing the method getSize(), to perform the method getSize(), which prints out the size of the object (like XL or 10.5) to the JTextArea. Now, because the class Clothes does not have a getSize() method (because not all clothes have definitive sizes. For example, Socks), I am having issues. The list is of type Clothes, so in the for-loop, I must declare the type of object as Clothes. But the piece is therefore also of type Clothes, so when I try to run getSize() on it, it gives me an error, because Clothes does not have a method getSize() in it. However, some of the objects in list do have this method. So my question is how to access this method for objects in the ArrayList list which is of type Clothes.
shoe, but cast toShoe. Is this typo?shoestarting with lower case, andShoestarting with upper case. Different things. When you say 'doesn't work', what do you mean? Have you any exceptions?piece instanceof shoenot bepiece instanceof Shoe