0

To reference a specific object inside an Array, i need to cast int to it's type or the compiler do not accept, why do i need this casting?

Exemple:

Person[] people = Person[5];            //Generic Array of specific objects

Employee employee1 = new Employee();    //Employee class extends Person
Manager manager1 = new Manager();       //Manager class extends Person

people[0] = employee1;
people[1] = manager1;


Person ref = people[0];                //OK! it can compile
Employee ref2 = people[1];               //Do not compile
Employee ref2 = (Employee) people[1];      //OK! it can compile

Why do the cast is necessary?

Lucas Marinzeck
  • 313
  • 4
  • 11
  • 1
    Because `people` type is `Person` -> `Person[] people = Person[5];` Compiler don't know `Employee extends Person` and you need to say it. – KunLun Apr 03 '19 at 16:28

4 Answers4

2

In Java there is a concept of upcasting and downcasting. Upcasting means casting to supertype whereas, downcasting means casting to a subtype.

Whenever there is an Is-A relationship you can do upcasting without any harm. But it is downcasting which needs to be taken care of.

For example You have People array and since both Employee and Manager classes extends People so People array can store both of these. Now when you do Employee ref2 = people[1]; compiler doesn't know that is it actually Employee as there is equal probability that in can be Manager as Manager class also extends People . So you need to explicitly provide a cast which tells compiler that you know what you are doing and no need to give any compile error. But if there is any issue at runtime then a ClassCastException will be thrown.

Yug Singh
  • 3,112
  • 5
  • 27
  • 52
1

It is not compiled without casting since people[1] is not known to the compiler to be an Employee.

From Java tutorial. Casting Objects:

We can tell the compiler that we promise to assign Employee to people[1] by explicit casting.

This cast inserts a runtime check that people[1] is assigned a Employee so that the compiler can safely assume that people[1] is a Employee. If people[1] is not a Employee at runtime, an exception will be thrown.

See more Casting variables in Java

Community
  • 1
  • 1
Ruslan
  • 6,090
  • 1
  • 21
  • 36
1

Type of variable people is Person. Person[] people = Person[5]; (type[] people = new instance - instance could also be child which extends type).

Here Employee ref2 = people[1]; compiler see people as Person and you need to say at compiler it also can be Employee(cause Employee extends Person) by casting.

You can read more, about this subject, here: https://www.baeldung.com/java-type-casting

KunLun
  • 3,109
  • 3
  • 18
  • 65
0

Because you have an Employee ref and you try to instantiate it with a value with the type Person.

Employee is a Person, but a Person is not necessarily an Employee. Correct me, if I'm wrong.

Hamza Ince
  • 604
  • 17
  • 46