I came across some code and cannot understand a certain aspect of it although i have done some extensive searching!
My question is: why are classes sometimes declared within parentheses like in the following code?
public class Animal {
public static void hide() {
System.out.println("The hide method in Animal.");
}
public void override() {
System.out.println("The override method in Animal.");
}
}
public class Cat extends Animal {
public static void hide() {
System.out.println("The hide method in Cat.");
}
public void override() {
System.out.println("The override method in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = (Animal)myCat;
myAnimal.hide();
myAnimal.override();
}
}
where my focus is on this line of code in particular:
Animal myAnimal = (Animal)myCat;
I believe it has something to do with the fact that one class extends another but am unsure what the class defined within parentheses signifies.
Any help on this is appreciated. Thank you in advance.
What you’re seeing is a cast to tell the compiler it’s ok to assign a Cat to an Animal.
Casts are for cases where the compiler can’t safely convert one type to another, either because it doesn’t know what the types involved are, or because the conversion would lose information (for instance, if you have a double that you want to store in a variable of type float).
In your example the cast is totally unnecessary because Cat extends Animal; since all Cats are Animals, the compiler doesn’t need an explicit cast to tell it it can assign a Cat to an Animal.
Casting should be reserved for special occasions. If you use explicit casts regularly then it may mean you’re not getting the most benefit out of the type system.