In below example
why should I type cast " CellPhone cellPhone = (CellPhone) o;" instead of directly accessing "Objects.equals(vendor, o.vendor) &&
Objects.equals(model, o.model);" ?. When I use "o." it gives oblect not found though its passed as part of parameter.
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CellPhone cellPhone = (CellPhone) o;
return Objects.equals(vendor, cellPhone.vendor) &&
Objects.equals(model, cellPhone.model);
}
level 11 lesson 6 first task - Pls help me understand why type casting needed
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
14 December 2021, 17:57
Through polymorphism you are able to declare a variable of one type and set the object to the type of any of the variables descendants. To recap, this is how a variables and objects are declared/created:
|---variable---| |---object---|
SomeClass var = new SomeClass();
The Object class is the base class of all classes/objects in Java so can be used as a variable type for any object. The methods and fields of the variable type are the only methods and fields that you will have access to no matter the type of object that is created. Here is an example:
0
Guadalupe Gagnon
14 December 2021, 17:59
With the code that you shared, the variable 'o' is of type Object, which means it can not access the fields in the CellPhone class unless it is first cast to a CellPhone. Therefore both "o.vendor" and "o.model" are not available and are causing the error that you are experiencing.
0
Gellert Varga
15 December 2021, 21:24
I'd like to add: this equals() method, when it receives an object of any type, converts it to Object type at the moment of reception (as the method parameter indicates it). Just to be able to receive any object, without Exception. It's an automatic type casting.
+1