First let’s start using the correct nomenclature of things, what you call an attribute is actually a field, then is repeating the same thing in the statement, improving your question and punctuating:
Like objects c1
and c2
are of the type Criatura
and does not have the methods and specialized fields of derived classes, correct?
No, these objects have the structure of the types that were used to create them, in this case the type Felino
and Ave
respectively. Therefore, knowing this, I imagine it is already getting easier to understand how the compiler knows.
When you declare which type of variable means only that the whole treatment will consider that the object is of this type, but this is abstract, the concrete object is of the most specialized type, what is in memory is the object that was created.
The variable being of the most general type the code can only access the members that are available in it, even if the concrete object has other members of the extended type nothing can be accessed, is an artificial prohibition of protection, is not a technical limitation.
The first cast is just saying that the object should be considered something like a Felino
, so right now you’re giving the right of access to all members of this type and so you can store in a variable of type Felino
. The members of Criatura
will remain accessible because all types Felino
have access to these members. Note that this has no processing cost.
The second is trying to do the same thing, but is giving access to members of Felino
to an object that concretely is a Ave
, So you don’t have those intended members, so you make a mistake.
The compiler knows that c2
there’s a guy in variable (read the definition) - Criatura
- and a guy worth his - Ave
, therefore the value has its type known.
The common mistake that many people make is to understand that the variable is the value, variable is just the storage location with a name, and in static typing languages it has a type. The value has type in all programming languages (roughly always has some different, most Assembly’s would be example). Separate these two concepts from your mind and it’s easy to understand why the itcher knows the type.
Thank you very much, a friend explained to me and along with his explanation was very clear.
– Flavio Ramos