·  JAVA – Syntax – Terms – Downcasting

 

- Info:

  - Downcasting permits an object which is treated as superclass (Animal) to be treated as an object of subclass type (Dog)

  - Downcasting must be defined explicitly and it works only if object is being downcasted to one of the classes it extends.

  - By casting you are not changing the object, you are just labeling (treating) it differently.

 

- Example:

  - Create JAVA Console Application Test.java

 

    Test.java

    public class Test {

      public static void main(String[] args) {

        

        //UPCASTING.

        Person john  = new Soldier();           //Implicit upcasting Soldier to Person.

               john.attack();  

               //john.bullets = 10;             //Can't access bullets.

               

        //DOWNCASTING.

        if(john instanceof Soldier) {

          Soldier johnSoldier = (Soldier) john; //Explicit downcasting Person to Soldier.

                  johnSoldier.bullets = 10;     //Can access bullets.

        }

        

      }     

    }

    

    class Person {

      void attack() { System.out.println("Using fist."); }

    }

    

    class Soldier extends Person {

      public int  bullets = 100;

      void attack() { System.out.println("Using gun."); }

    }