Object Type Casting

Object Type Casting in Java

In Java, object type casting refers to the process of converting an object of one type to another type. It allows treating an object as an instance of a different class or interface. Type casting is required in certain scenarios to access specific behaviors or properties of an object that are not available in its original type.

Why is Object Type Casting Required?

Object type casting is required in Java for the following reasons:

  • To access specific methods or fields of an object that are only available in a particular class or interface.
  • To achieve polymorphism, where a subclass object can be treated as an instance of its superclass.
  • To utilize interfaces and their implementations interchangeably.
  • To convert between compatible reference types, such as superclass to subclass or interface to implementing class.

Example:

Consider a scenario where we have a class hierarchy consisting of a superclass called `Animal` and subclasses `Dog` and `Cat`:

    
      class Animal {
          public void makeSound() {
              System.out.println("Animal is making a sound");
          }
      }
      
      class Dog extends Animal {
          public void makeSound() {
              System.out.println("Dog is barking");
          }
          
          public void fetch() {
              System.out.println("Dog is fetching");
          }
      }
      
      class Cat extends Animal {
          public void makeSound() {
              System.out.println("Cat is meowing");
          }
          
          public void scratch() {
              System.out.println("Cat is scratching");
          }
      }
    
  

Now, let's see how object type casting can be used in different scenarios:

    
      Animal animal = new Dog();
      animal.makeSound(); // Output: "Dog is barking"
      ((Dog) animal).fetch(); // Output: "Dog is fetching"
      
      Animal animal2 = new Cat();
      animal2.makeSound(); // Output: "Cat is meowing"
      ((Cat) animal2).scratch(); // Output: "Cat is scratching"
    
  

In the above example, we create an object of the `Dog` class and assign it to a variable of the `Animal` type. By using object type casting, we can call the `fetch()` method specific to the `Dog` class.

Similarly, we create an object of the `Cat` class and assign it to another `Animal` variable. With object type casting, we can call the `scratch()` method specific to the `Cat` class.

Object type casting allows us to treat objects polymorphically and access specific behaviors or properties based on their actual types. It provides flexibility and enables code reusability in various scenarios.

Go To OOPS Page Click Here

Post a Comment

Previous Post Next Post