Casting in Java
In Java, casting is a process of converting one data type to another. When you cast an object reference from one class to another, it is known as upcasting or downcasting depending on the relationship between the classes.
Upcasting is when you cast an object of a subclass to a superclass reference. This is always safe and does not require an explicit cast. For example:
javaclass Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Bark");
}
}
Dog myDog = new Dog();
Animal myAnimal = myDog; // upcasting, no explicit cast required
In the above example, the object myDog is upcasted to the Animal reference myAnimal. Since Dog is a subclass of Animal, this is always safe.
Downcasting is when you cast an object of a superclass to a subclass reference. This is not always safe and requires an explicit cast. For example:
javaclass Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Bark");
}
}
Animal myAnimal = new Dog();
Dog myDog = (Dog) myAnimal; // downcasting, explicit cast required
myDog.makeSound(); // prints "Bark"
In the above example, the object myAnimal is first upcasted to the Animal reference. Later, we downcasted it back to the Dog reference using an explicit cast. Since myAnimal was originally created as a Dog, this is safe.
However, downcasting can lead to a ClassCastException at runtime if the object being downcasted is not actually an instance of the subclass. Therefore, it's important to use instanceof operator to check the type of object before performing the downcasting.
javaif (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal;
myDog.makeSound(); // prints "Bark"
}
Comments
Post a Comment