Skip to content
Advertisement

Print a value of an extended class object from mother class object

I’ve declared a table that has the mother class type and i’ve filled it with many objects that have the extended classe type, everything looks fine and the table is successfully filled, the problem is when i’m trying to access to the table values i cannot ( in the exemple i’m trying to get the salaire attribut )
MOTHER CLASS

JavaScript

SUB CLASS 1

JavaScript

main class

JavaScript

Advertisement

Answer

You have told the compiler that tab contains personne objects. The compiler only knows what you tell it.

The compiler does not execute your program. It doesn’t know that your program may have added an employé instance to the array. For that matter, it doesn’t follow every method call in your program checking for whether any of those methods might have added different objects.

Since the compiler can only know for certain that tab contains objects of type personne or possibly a subtype of it, you will have to check each element’s type yourself:

JavaScript

If you are using a version of Java older than Java 14, you will have to perform the cast manually:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement