The error happens because you are using the property length directly into the object (teste
) of your class Carta
.
Instead, you can access the array that belongs to your class (assuming it is public and has already been initialized) as follows:
Carta teste = new Carta();
for (int i = 0; i < teste.arrayDesejado.length; i++)
{
if (teste.arrayDesejado[i] instanceof Figuras) {}
}
Obs: another inconsistency is due to the use of instanceof (written entirely in lower case). In your code, you are testing whether teste
is an instance of Figuras
, which will never be true because it is already an instance of Carta
. The same happens with my example above: arrayDesejado
has a pre-established type in its definition; therefore, as this type is immutable, it would not be convenient to test whether a given position of the array holds an instance of a specific class or subclass.
An alternative would be to use a Arraylist within your class Carta
to store the objects:
ArrayList<Object> listaDeObjetos = new ArrayList<Object>();
Then, to check which objects were added to the list you could use a loop that went through all its elements:
for (Object obj : teste.listaDeObjetos)
{
if (obj instanceof Figuras) {}
}
I used just one example in this case I’m working the class
Carta
is actually a name classGinasio
, which is a super class, which is why I make use of theinstanceof
. As to theArrayList
, I actually asked the teacher this question, but he said that in this exercise they wanted to use an array..– gustavo