Access attributes of type Object

Asked

Viewed 240 times

1

I’m having trouble accessing values from an Object attribute. I have a No class that has No attributes, and Object Item.

Each item is an object of the Subject class.

I queue the items of the class No normally, however when I try to print, I get only the item object as return... How do I enter the Object type (item) and access the Subject attributes?

This code is responsible for printing:

public void imprime() {
    System.out.println(size);
    for (int i = 0; i < size; i++) {
    System.out.println("Desc:"+ head.item);
        head = head.getProximo();
    }
}

1 answer

1

If items are always Subjects, why don’t you declare as Subject and not as Object?

Anyway, if you don’t want/can change this, to access the Subject attributes, you need to cast, so java will try to convert the object to the type you want, you do this by specifying the type in parentheses.

System.out.println("Desc:"+ ((Assunto)head.item).propriedadeDeAssunto);

Another tip, it is not good practice to access properties directly, instead make the properties private and create get and set methods to access the values, so you keep the encapsulation. If you’re still studying and haven’t seen it, you’ll see in the future.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.