In this lesson, you will learn
In Java, casting refers to converting a variable from one data type to another. Upcasting and downcasting are specific types of casting that occur within an inheritance hierarchy.
Before diving into upcasting and downcasting, it’s crucial to understand inheritance. In Java, inheritance allows a class (subclass or derived class) to inherit properties and methods from another class (superclass or base class).
package ch9.l3;
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class TestUpcasting {
public static void main(String[] args) {
Dog myDog = new Dog();
// Upcasting Dog to Animal
Animal myAnimal = myDog; // Implicit upcasting
myAnimal.eat(); // Works fine, output: Animal is eating
// Calling myAnimal.bark() would result in a compile-time error
// because the reference type Animal does not have a bark method.
}
}
Animal is eating
In this example, Dog is a subclass of Animal. By assigning myDog (of type Dog) to myAnimal (of type Animal), we’re performing upcasting. After upcasting, myAnimal can only access methods declared in Animal (or its superclasses), not those unique to Dog.
ClassCastException at runtime if the object being cast is not actually an instance of the target subclass.package ch9;
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class TestDowncasting {
public static void main(String[] args) {
// Superclass variable referencing a subclass object
Animal myAnimal = new Dog(); // Upcasting, implicitly
// This will call the eat method from Animal class
myAnimal.eat();
// However, the following line would cause a compile-time error because
// the reference type Animal does not have access to the bark method.
// myAnimal.bark(); //Uncommenting this line would result
// in a compilation error
// Downcasting back to Dog
if (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal; // Explicit downcasting
myDog.bark(); // Works fine, output: Dog is barking
}
}
}
Animal is eating Dog is barking