I have a question regarding the class definition in Java. With respect to the following code segment, after the if
switch already verifies that h is an instance of Animal
, why we still need to add the line of Animal ob = (Animal) h
? In addition, why the second coding segment is wrong? I know it should come from the line of public boolean equals (Animal h)
Object.equals()
takes an object of type Object
, so the second example is wrong because it takes an Animal
object instead. In the first one, the cast is because the variable has type Object
, even though it actually is an instance of the Animal
type, so it needs to be cast to be assigned to a variable of type Animal
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments